【问题标题】:android + google map api v2 + current locationandroid + google map api v2 + 当前位置
【发布时间】:2013-04-14 22:42:21
【问题描述】:

我正在创建一个带有谷歌地图视图的应用程序,我希望这个应用程序检测用户的当前位置并在地图上用标记显示纬度和经度,但到目前为止我所能做的只是显示谷歌地图和当前位置的检测没有显示任何标记,也没有任何文本显示经纬度

直到现在我才添加标记,因为我不知道将它放在代码中的哪个位置以及这样做的最佳做法是什么

谁能帮帮我??? 这是以下代码:

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.locationgooglemapv2demo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <permission
        android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.wptrafficanalyzer.locationgooglemapv2demo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="API KEY" />
    </application>

</manifest>

xml文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>

java 文件

package in.wptrafficanalyzer.locationgooglemapv2demo;

import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

public class MainActivity extends FragmentActivity implements LocationListener {

    GoogleMap googleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);

            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

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

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

            // Getting Current Location
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null){
                onLocationChanged(location);
            }
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        }
    }
    @Override
    public void onLocationChanged(Location location) {

        TextView tvLocation = (TextView) findViewById(R.id.tv_location);

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

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

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

        // Showing the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

        // Setting latitude and longitude in the TextView tv_location
        tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

【问题讨论】:

    标签: android google-maps


    【解决方案1】:

    首先查看文档here,它很好地说明了获取用户位置的最佳策略。

    就我个人而言,我通常在地图开始时将标记放置在检索到的位置

    Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
    

    然后我开始监听位置更新并移动标记。

    这还取决于您应用程序所需的准确位置,如果您不需要非常准确的位置但面积足够,也许您可​​以使用lastKnownLocation

    你可以试试这样的

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
    
        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
    
            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();
    
        }else { // Google Play Services are available
    
            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    
            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();
    
            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);
    
            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    
            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();
    
            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);
    
            // Getting Current Location
            Location location = locationManager.getLastKnownLocation(provider);
    
            LocationListener locationListener = new LocationListener() {
              void onLocationChanged(Location location) {
              // redraw the marker when get location update.
              drawMarker(location);
            }
    
            if(location!=null){
               //PLACE THE INITIAL MARKER              
               drawMarker(location);
            }
            locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);
        }
    }
    
    private void drawMarker(Location location){
        // Remove any existing markers on the map
        googleMap.clear();
        LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
        googleMap.addMarker(new MarkerOptions()
        .position(currentPosition)
        .snippet("Lat:" + location.getLatitude() + "Lng:"+ location.getLongitude())
        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
        .title("ME"));
    }
    

    另外你不需要implements LocationListener的Activity类,你可以像我上面那样定义一个监听器并注册它

    附:我没有编辑器,我的代码可能包含拼写错误

    希望对你有帮助,干杯

    【讨论】:

    • @drChivas 这正是我想要做的,我需要在地图上显示用户的当前位置,并带有包含 lat 和 long 的文本,但我不知道该怎么做跨度>
    • 如果最后一个已知位置为空怎么办
    • 这太棒了,而且物有所值。仅供参考,这是一个语法错误: .sn-p("Lat:" + location.getLatitude() + "Lng:"+ location.getLongitude()));我不得不删除最后的括号和分号,因为它使以下 .icon() 等部分无效。
    • @DrChivas 可以告诉我,如果我按下右侧的地图按钮,如何显示当前位置
    【解决方案2】:

    我刚刚遇到了同样的问题,并找到了使用 Google Maps API 的方法:

    private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {
            LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
            mMarker = mMap.addMarker(new MarkerOptions().position(loc));
            if(mMap != null){
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
            }
        }
    };
    

    然后为地图设置监听器:

        mMap.setOnMyLocationChangeListener(myLocationChangeListener);
    

    这将在地图第一次找到位置时被调用。

    根本不需要LocationServiceLocationManager

    【讨论】:

    • 这按预期工作。谢谢。但我想修改它以能够返回一个包含 lat 和 lng 的 double[]。这怎么可能?这对我来说看起来很奇怪。 ://
    【解决方案3】:

    在android中定义谷歌地图android v2的完整快捷方式......

    XML 文件:

    <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    

    菜单文件:

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
    <!-- Map permission Starts -->
    <permission
        android:name="com.example.mapdemoapiv2.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />
    
    <uses-permission android:name="com.example.mapdemoapiv2.permission.MAPS_RECEIVE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />
    
    <!-- Map permission Starts -->
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mapdemoapiv2.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MapDetail" >
        </activity>
    
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="Your Key" />
    
        <uses-library android:name="com.google.android.maps" />
    </application>
    

    活动类:

    public class MainActivity extends android.support.v4.app.FragmentActivity
    {
       GoogleMap googleMap;
        MarkerOptions markerOptions;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        setUpMapIfNeeded();
    
        GetCurrentLocation();
    
        }
    
    private void setUpMapIfNeeded() {
        if (googleMap == null) {
    
            Log.e("", "Into null map");
            googleMap = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
    
            googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(
                    MainActivity.this));
    
            if (googleMap != null) {
                Log.e("", "Into full map");
                googleMap.setMapType(googleMap.MAP_TYPE_NORMAL);
                googleMap.getUiSettings().setZoomControlsEnabled(false);
            }
        }
    }
    
    private void GetCurrentLocation() {
    
        double[] d = getlocation();
        Share.lat = d[0];
        Share.lng = d[1];
    
         googleMap
                .addMarker(new MarkerOptions()
                        .position(new LatLng(Share.lat, Share.lng))
                        .title("Current Location")
                        .icon(BitmapDescriptorFactory
                                .fromResource(R.drawable.dot_blue)));
    
                 googleMap
                    .animateCamera(CameraUpdateFactory.newLatLngZoom(
                            new LatLng(Share.lat, Share.lng), 5));
    }
    
    public double[] getlocation() {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = lm.getProviders(true);
    
        Location l = null;
        for (int i = 0; i < providers.size(); i++) {
            l = lm.getLastKnownLocation(providers.get(i));
            if (l != null)
                break;
        }
        double[] gps = new double[2];
    
        if (l != null) {
            gps[0] = l.getLatitude();
            gps[1] = l.getLongitude();
        }
        return gps;
    }
    

    【讨论】:

    • 我们可以通过 Google Maps API 获取位置吗?因为有些设备没有 GPS。
    【解决方案4】:

    最好用:

    Location currentLocation =
         LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
    

    Documentation

    【讨论】:

      【解决方案5】:

      就这么简单:

      在这之后 -

      <meta-data
          android:name="com.google.android.maps.v2.API_KEY"
          android:value="Your Key" />
      

      放这个——

      <meta-data android:name="com.google.android.gms.version" android:value="4030500" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-30
        • 1970-01-01
        • 2013-08-27
        • 1970-01-01
        • 1970-01-01
        • 2015-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多