草庐IT

java - 我需要比较纬度和经度坐标,这将告诉 GPS 用户哪家 Hooters 餐厅离他当前位置最近

coder 2023-12-03 原文

我已经完成了查找威斯康星州所有 6 家 Hooters 餐厅位置的准确纬度/经度(十进制数字表示法)坐标的准备工作。我打算将这些坐标值存储在一个单独类的数组中。我的代码中也已经有一个 Location Listener 来获取用户当前的 GPS 位置。请参阅下面的代码:

package sam.finalmap.hooters;


// Camera is the view of the map.

import com.google.android.gms.maps.CameraUpdateFactory;
// the google map
import com.google.android.gms.maps.GoogleMap;


import android.app.Activity;
import android.content.Context;

import android.graphics.Color; // for drawing a line.

import android.location.Location; // for detecting location changes with the GPS.
import android.location.LocationListener; // to listen for location changes
import android.location.LocationManager;
import android.os.Bundle;

import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.MapFragment;  // the Map class.
import com.google.android.gms.maps.model.LatLng; // for creating lattitudes and longitutes in memory.
import com.google.android.gms.maps.model.Polyline; // used to draw from one location to the other
import com.google.android.gms.maps.model.PolylineOptions;

/**
 * Draws a map, uses GPS to get the current location, the draws a line from Eau CLaire (see constants)
 * to the new position, which will be the closest Hooters restaurant to the user's current location. 
 * This is the AdapterView.
 * 
 * @author daviddalsveen
 *
 */
public class GMapsLocationPath extends Activity implements LocationListener {
    /** Called when the activity is first created. */

    private GoogleMap mMap;

    // constants to hard code all 6 of Wisconsin's Hooters restaurant points on the map:

    private static final float Appleton_LAT = 44.2655012f;

    private static final float Appleton_LNG = -88.4768057f;


    private static final float Brookfield_LAT = 43.03645f;

    private static final float Brookfield_LNG = -88.124937f;


    private static final float EastMadison_LAT = 43.132432f;

    private static final float EastMadison_LNG = -89.3016256f;


    private static final float GreenBay_LAT = 44.477903f;

    private static final float GreenBay_LNG = -88.067014f;


    private static final float Janesville_LAT = 42.7215666f;

    private static final float Janesville_LNG = -88.9889661f;


    private static final float LaCrosse_LAT = 43.8109318f;

    private static final float LaCrosse_LNG = -91.2536215f;



    private LocationManager locationManager;

    private TextView tv;   // a Textview for displaying lattitude and longitude.

    private float curLat = 44.88f; // current position -- assigned constants for
                                    // testing...
    private float curLng = -91.47f;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // called when the activity is first started.

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // recommended method by google to make the map object.
        setUpMapIfNeeded();

        // Sets the map type to be "normal"
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        tv = (TextView) findViewById(R.id.label1);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                500, 1, this);
        Location location = locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        // 500 is the minimum time interval to update, in milliseconds
        // 1 is the distance in meters in which to sense an update.
        // 'this' is the pending intent.

        // center latitude and longitude for EC
        float lat = Appleton_LAT;
        float lng = Appleton_LNG;

        // debug example...
        Toast.makeText(this, "" + (int) (lat * 1E6), Toast.LENGTH_LONG).show();

        if (location == null) { // no last known location
            locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,
                    this, null);
            // Create a new Lattitude Longitude Object, passing it the
            // coordinates.
            LatLng latLng = new LatLng(lat, lng);

            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.0f));
            // re-draw

        } else {
            // explicitly call and update view with last known location or the
            // one set above.
            onLocationChanged(location);
        }

    }

    /**
     * Checks to see that the map exists, if not, creates one.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the
        // map.
        if (mMap == null) {
            mMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                // The Map is verified. It is now safe to manipulate the map.

            }// else?
        }
    }

    // Java Interface RULE NOTE: that we must implement every method of
    // interface LocationListener,
    // whether we use the method or not.
    /**
     * Use the GPS to get the current location of the user
     * 
     */
    public void onLocationChanged(final Location loc) {

        String lat = String.valueOf(loc.getLatitude());
        String lon = String.valueOf(loc.getLongitude());
        Log.e("GPS", "location changed: lat=" + lat + ", lon=" + lon);
        tv.setText("lat=" + lat + ", lon=" + lon);

        curLat = Float.parseFloat(lat); // update the current lattitude and longitude.
        curLng = Float.parseFloat(lon);

        // Create a new Lattitude Longitude Object, passing it the coordinates.
        LatLng latLng = new LatLng(curLat, curLng);

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.0f));
        // re-draw
        draw();

    }

    public void onProviderDisabled(String loc) {
        Log.e("GPS", "provider disabled " + loc);
    }

    public void onProviderEnabled(String loc) {
        Log.e("GPS", "provider enabled " + loc);
    }

    /**
     * loc: name of location provider status: status of location provider
     * (temporarily unavailable, etc) extras: optional bundle with additional
     * status information
     */
    public void onStatusChanged(String loc, int status, Bundle extras) {
        Log.e("GPS", "status changed to " + loc + " [" + status + "]");
    }

    /**
     * Draw a line from 
     */
    public void draw() {

        float lat = 44.88f;
        float lng = -91.48f;

        // Instantiates a new Polyline object and adds points to define a
        // endpoints of a line
        PolylineOptions rectOptions = new PolylineOptions().add(
                new LatLng(curLat, curLng))

                .add(new LatLng(lat, lng)); // Closes the polyline.

        // Set the rectangle's color to red
        rectOptions.color(Color.RED);

        // Get back the mutable Polyline
        Polyline polyline = mMap.addPolyline(rectOptions);      

    }   

} 

我在这里需要帮助的是找到一种方法来解析数组,并将用户位置与 6 个餐厅位置中的每一个的差异进行比较,以差异最小者为准(以距离用户最近的餐厅位置为准)是将要选择的餐厅,将显示谁的信息。

就是说,在完成对数组的解析并获得所有 6 个纬度/经度差异后,我如何告诉它使用最小的差异?

/**
     * My teacher suggested subtracting the current latitudes and longitudes from the restaurant latitudes and 
     * longitudes to see if they fall within a certain range (lets just say less than 10). Then, using the resulting 
     * differences as absolute values in an if statement (if absolute value < 10 for both are true), that restaurant
     * would be the one selected:  
     */

    //float[] H_Latitude = {44.2655012f, 43.03645f, 43.132432f, 44.477903f, 42.7215666f, 43.8109318f};  

    //float[] H_Longitude = {-88.4768057f, -88.124937f, -89.3016256f, -88.067014f, -88.9889661f, -91.2536215f};

    float LATdifference = curLat - H_Latitude; 

    float LNGdifference = curLng - H_Longitude;//I'm pretty sure I can't use "H_Longitude and H_Latitude", because
    //they're merely the name of the array. So how do I access the elements inside of them? How do I successfully
    //address them with a reference variable that I can use to dynamically subtract from curLat and curLng and get
    //what I need to replace the "i" in the for loops:
                                            for (float LATdifference = 0; i < 4; i++) {
                                                System.out.println (count[i]);
                                                  }

最佳答案

试试 Location.distanceBetween(): reference

关于java - 我需要比较纬度和经度坐标,这将告诉 GPS 用户哪家 Hooters 餐厅离他当前位置最近,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15304468/

有关java - 我需要比较纬度和经度坐标,这将告诉 GPS 用户哪家 Hooters 餐厅离他当前位置最近的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  3. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  4. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  5. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  6. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

  7. 【Java 面试合集】HashMap中为什么引入红黑树,而不是AVL树呢 - 2

    HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候

  8. 【Java入门】使用Java实现文件夹的遍历 - 2

    遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg

  9. java - 为什么 ruby​​ modulo 与 java/other lang 不同? - 2

    我基本上来自Java背景并且努力理解Ruby中的模运算。(5%3)(-5%3)(5%-3)(-5%-3)Java中的上述操作产生,2个-22个-2但在Ruby中,相同的表达式会产生21个-1-2.Ruby在逻辑上有多擅长这个?模块操作在Ruby中是如何实现的?如果将同一个操作定义为一个web服务,两个服务如何匹配逻辑。 最佳答案 在Java中,模运算的结果与被除数的符号相同。在Ruby中,它与除数的符号相同。remainder()在Ruby中与被除数的符号相同。您可能还想引用modulooperation.

  10. java - Ruby 相当于 Java 的 Collections.unmodifiableList 和 Collections.unmodifiableMap - 2

    Java的Collections.unmodifiableList和Collections.unmodifiableMap在Ruby标准API中是否有等价物? 最佳答案 使用freeze应用程序接口(interface):Preventsfurthermodificationstoobj.ARuntimeErrorwillberaisedifmodificationisattempted.Thereisnowaytounfreezeafrozenobject.SeealsoObject#frozen?.Thismethodretur

随机推荐