【问题标题】:cannot display current position on google map v2无法在谷歌地图 v2 上显示当前位置
【发布时间】:2015-02-10 06:25:49
【问题描述】:

我正在开发一个 android 应用程序,其中显示带有标记的地图。每次在我的移动 android 设备上使用 WI-FI/3G/GPS 时,我都会尝试读取并显示我的当前位置。我遇到的问题是我在我的地图上看不到打印的标题和 sn-p。 我的代码如下。

私人无效 setUpMap() {

    mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));


    // Enable MyLocation Layer of Google Map
    mMap.setMyLocationEnabled(true);

    // Enable / Disable my location button
    mMap.getUiSettings().setMyLocationButtonEnabled(true);

    // Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Get the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);


    // Get Current Location
    Location myLocation = locationManager.getLastKnownLocation(provider);


    // set map type
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);   // MAP_TYPE_HYBRID

         // Get latitude of the current location
         double latitude = myLocation.getLatitude();

         // Get longitude of the current location
         double longitude = myLocation.getLongitude();

         // Create a LatLng object for the current location
         LatLng latLng = new LatLng(latitude, longitude);

         // Show the current location in Google Map
         mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

         // Zoom in the Google Map
         mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
         mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("I am here!").snippet("success located"));

     }

}

基于我的 Maps Activity.java 文件的上述代码,由于错误空指针异常,我从未看到标题“我在这里”:

双纬度 = location.getLatitude();

我该如何解决这个问题?

我昨天出于测试目的尝试了以下方法:

//启用谷歌地图的MyLocation层

    mMap.setMyLocationEnabled(true);

    // Enable / Disable my location button
    mMap.getUiSettings().setMyLocationButtonEnabled(true);

    // Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Get the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);


    // Get Current Location
    Location myLocation = locationManager.getLastKnownLocation(provider);


    // set map type
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);   // MAP_TYPE_HYBRID

     if(myLocation != null) {
         // Get latitude of the current location
         double latitude = myLocation.getLatitude();

         // Get longitude of the current location
         double longitude = myLocation.getLongitude();

         // Create a LatLng object for the current location
         LatLng latLng = new LatLng(latitude, longitude);

         // Show the current location in Google Map
         mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

         // Zoom in the Google Map
         mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
         mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("I am here!").snippet("Consider yourself located"));
                        } //case myLocation not null
                             else { //do nothing
                                                 }
     }

}

在通过 wi-fi 连接到 3 个不同的地方后,我尝试打开我的 api 至少 10 次。在我打开 api 的 90% 的时间里,我在蓝色圆圈中看到了我正确的当前位置。 10% 的时间我打开我的 api 我看到一个红色标记显示消息“我在这里!”(通常是当我在我的手机上禁用然后启用位置设置时)以及蓝色圆圈......这意味着大多数有多少次我试图获取提供商(网络:wi-fi)的位置失败了?这是供应商的问题...?

过去我开发了另一个基于 javascript、CSS、html 代码的项目 Web 界面。我使用了 getCurrentLocation-javascript,它 100% 显示了正确的当前位置(我在一天内尝试了 10 个不同的地方以及我得到的所有当前位置都正确)。 javascript获取当前位置功能是否比java更可靠?

【问题讨论】:

    标签: android google-maps


    【解决方案1】:

    在调用方法之前,您需要检查您的 myLocation 变量。在某些情况下,我可以并且将会为空。

    所以只需检查它是否为空,如果是则从函数返回并稍后再次调用它,最终它将是有效的,然后您可以获取纬度和经度并添加标记。当您第一次启动应用程序并且您使用 gps 作为提供程序并且它尚未获得修复时,可能会发生这种情况。如果这是从位置更改触发的某些内容中调用的,那么您需要做的就是忽略返回值为 null 的情况,因为一旦位置可用,将再次调用此方法。

    http://developer.android.com/reference/android/location/LocationManager.html#getLastKnownLocation%28java.lang.String%29

    public Location getLastKnownLocation(字符串提供者)在 API 中添加 1级

    返回一个 Location 指示来自最后一个已知位置的数据 从给定的提供程序获得的修复。

    这可以在不启动提供程序的情况下完成。请注意,这 位置可能已过时,例如,如果设备已转动 关闭并移动到另一个位置。

    如果提供程序当前被禁用,则返回 null。参数 provider 提供者名称 返回

    the last known location for the provider, or null
    

    【讨论】:

    • 我很想知道为什么这个答案被否决(所以我可以改进它)
    【解决方案2】:

    根据经验,有时接收您的第一个位置需要时间并导致 nullpointerexception。这很常见。我在 Android SDK 的文档中四处寻找,发现了LocationListener。根据文档,当它满足您在方法中给定的参数时,它会获取您的位置。

    首先在您的Activity 中开发两个新方法,并在您的setupMap() 方法之外初始化locationManager.. 并添加一个新变量。 (确保在 setupMap() 方法中删除 'LocationManager' locationManager。)

    LocationManager locationManager;
    
    boolean gotLocation = false;
    
    public boolean validLatLng(double lat, double lng) {
        if(lat != null && lng != null) {
            this.gotLocation = true;
            return true;
        } else return false;
    }
    
    public boolean haveLocation() { return this.gotLocation; }
    

    该方法非常简单,不需要进一步解释。

    让我们为你创建一个新的 LocationListener..

    LocationListener mLocationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Do what you need to do.
        }
    }
    

    如您所见,我们没有在 LocationListener 的构造函数中提供任何参数,因为它没有需要一些参数的构造函数,并且在 onLocationChanged() 方法中没有任何新内容

    例如,您希望从 Activity 运行的点获取第一个位置,这是可以的。现在让我们将 Map Activity 中的新方法使用到 mLocationListeneronLocationChanged() 方法中。

    LocationListener mLocationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if(!haveLocation() && validLatLng(location.getLatitude(), location.getLongitude()) {
                Log.i("mLocationListener", "Got a location!");
    
                // Stops the new update requests.
                locationManager.removeUpdates(mLocationListener);
    
                // Get latitude of the current location
                double latitude = location.getLatitude();
    
                // Get longitude of the current location
                double longitude = location.getLongitude();
    
                // Create a LatLng object for the current location
                LatLng latLng = new LatLng(latitude, longitude);
    
                // Show the current location in Google Map
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    
                // Zoom in the Google Map
                mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
                mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("I am here!").snippet("success located"));
    
            }
        }
    }
    

    onLocationChanged() 现在检查它是否已经有一个位置,如果没有,那就太好了,然后继续我们的下一个要求,将它推入 if 语句。当validLatLng() 成功并返回true 时,它​​会进入if 语句,在LogCat 中输入一个新字符串并禁止LocationManager 进一步更新并将您的一些代码复制粘贴到onLocationChanged() 方法中。

    现在我们已经完成了所有设置,让我们添加新内容/修改您的 setupMap() 方法。

    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    
        // Enable MyLocation Layer of Google Map
        mMap.setMyLocationEnabled(true);
    
        // Enable / Disable my location button
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
    
        // Get LocationManager object from System Service LOCATION_SERVICE
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    
        // Create a criteria object to retrieve provider
        Criteria criteria = new Criteria();
    
        // Get the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);
    
        // set map type
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);   // MAP_TYPE_HYBRID
    
        // Start new code by kevto.
        locationManager.requestLocationUpdates(provider, 1000, 0.0f, mLocationListener); // (String) provider, time in milliseconds when to check for an update, distance to change in coordinates to request an update, LocationListener.
        // End new code by kevto
    }
    

    结果,它会在收到更新时检查您的位置,如果有有效的位置,它将阻止应用一遍又一遍地检查您的位置并将标记添加到您的地图中。

    我自己还没有测试过,可能会出现一些错别字,但它应该可以根据 Android 的文档工作。

    【讨论】:

    • 非常感谢您的回答。它得到了很好的解释和记录,帮助我理解代码功能!我会尝试您提出的解决方案。
    • 啊,当然。感谢提及。当我写这篇文章时并没有真正考虑它:)!
    • 编译成功,运行api。我没有看到“我在这里!”和蓝色圆圈标记上的“成功定位”(wi-fi,启用 GPS)。行为就像显示最后一个已知位置。在这种情况下,我会看到这条消息吗?如果我将手机连接到新位置(不同的网络提供商?)..?
    • 你看到“有一个位置!”在你的 logcat 中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    相关资源
    最近更新 更多