简体   繁体   English

android + google map api v2 +当前位置

[英]android + google map api v2 + current location

i am creating an app with a google map view and i want this app to detect the current location of the user and display the lat and long with a marker on the map but all i can do until now is the display of the google map and the detection of current location without any marker displayed and without any text appear to display the lat and long 我正在使用谷歌地图视图创建一个应用程序,我希望这个应用程序检测用户的当前位置,并在地图上显示lat和long标记,但我现在所能做的只是显示谷歌地图和在没有显示任何标记且没有任何文本的情况下检测当前位置似乎显示lat和long

i did not add a marker until now because i do not know where to put it in the code and what is the best practice to do that 我直到现在才添加标记,因为我不知道将其放在代码中的哪个位置以及执行此操作的最佳做​​法是什么

can anyone help me ??? 谁能帮我 ??? this is the code of the: 这是代码:

manifest file 清单文件

<?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 file 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 file 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;
    }
}

First check the documentation here , it gives good indication on best strategies for getting user position. 首先查看此处的文档,它可以很好地指示获取用户位置的最佳策略。

Personally I usually start the map with a marker placed at the position retrivied with 就个人而言,我通常会在地图上放置一个标记,并将其放置在经过重新检查的位置

Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

and then I start listening for position update and move the marker. 然后我开始听取位置更新并移动标记。

It also depend on how accurate position you need for the pourpose of your application, if you don't need really accurate position but the area is sufficient maybe you can just use the lastKnownLocation . 它还取决于您的应用程序所需的准确位置,如果您不需要真正准确的位置但面积足够,也许您可​​以使用lastKnownLocation

You can try something like this 你可以尝试这样的事情

@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"));
}

Also you don't need the Activity class to implements LocationListener , you can just define a listener and register it as I did above 此外,您不需要Activity类来implements LocationListener ,您可以像上面一样定义一个侦听器并注册它

PS I don't have an editor son my code can contain typo PS我没有编辑儿子我的代码可以包含拼写错误

Hope this helps, cheers 希望这会有所帮助,欢呼

I just had the same problem, and found a way to do it using the Google Maps API: 我遇到了同样的问题,并找到了使用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));
        }
    }
};

and then set the listener for the map: 然后为地图设置监听器:

    mMap.setOnMyLocationChangeListener(myLocationChangeListener);

This will get called when the map first finds the location. 当地图首次找到该位置时,将调用此方法。

No need for LocationService or LocationManager at all. 根本不需要LocationServiceLocationManager

Full shortcut for defining the Google Map android v2 in android...... 在android中定义Google Map android v2的完整快捷方式......

XML File : XML文件:

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

Menifest file : 清单档案:

<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>

Activity class : 活动类:

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;
}

It is better to use: 最好使用:

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

Documentation 文档

easy like that: 很容易:

after this - 在这之后 -

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

put this - 把这个 -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM