【问题标题】:Mark current location on google map在谷歌地图上标记当前位置
【发布时间】:2013-09-03 23:16:41
【问题描述】:

如何在谷歌地图上标记我的当前位置?

我正在使用 Google Place API。我必须从我当前的位置显示所有附近的地方。所有地点都显示在谷歌地图上,但如何显示我当前的位置? 代码如下:

public class PoliceStationMapActivity extends FragmentActivity implements LocationListener {
    private ArrayList<Place> mArrayListPoliceStations;
    private GoogleMap mMap;
    private LocationManager locManager;
    private double latitude;
    private double longitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_police_station);

    locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
        locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    else
        Log.i("Test", "network provider unavailable");

    Location lastKnownLocation = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    latitude = lastKnownLocation.getLatitude();
    longitude = lastKnownLocation.getLongitude();

    if (lastKnownLocation != null) {
        Log.i("Test", lastKnownLocation.getLatitude() + ", " + lastKnownLocation.getLongitude());
        locManager.removeUpdates(this);
    }

    mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    if (mMap != null) {
        new GetAllPoliceStationsTask().execute("" + latitude, "" + longitude);
    }
}

private class GetAllPoliceStationsTask extends AsyncTask<String, Void, ArrayList<Place>> {
    @Override
    protected ArrayList<Place> doInBackground(String... param) {
        ArrayList<Place> policeStationsList = RequestHandler.getInstance(PoliceStationMapActivity.this).getAllPlaces(param[0], param[1]);
        return policeStationsList;
    }

    @Override
    protected void onPostExecute(java.util.ArrayList<Place> result) {
        if (result != null) {
            mArrayListPoliceStations = result;
            placeAllPoliceStationMarkersOnMap(mArrayListPoliceStations);
        }
    }

}

private void placeAllPoliceStationMarkersOnMap(ArrayList<Place> policeStationList) {
    for (Place place : policeStationList) {
        addPlaceMarkerOnMap(place);
    }
};

private void addPlaceMarkerOnMap(Place place) {
    LatLng latLng = new LatLng(place.getLatitude(), place.getLongitude());
    Marker poiMarker = mMap.addMarker(new MarkerOptions().position(latLng).title(place.getName()).snippet(place.getVicinity()));
    Marker currentMarker = mMap.addMarker(new MarkerOptions().position());
}

@Override
public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
}

@Override
public void onProviderDisabled(String provider) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}`

【问题讨论】:

    标签: android google-maps-api-3 android-mapview android-maps


    【解决方案1】:

    首先,获取当前位置:

    private Location mCurrentLocation;
    mCurrentLocation = mLocationClient.getLastLocation();
    

    阅读here了解更多信息。

    然后您可以使用以下命令指向该位置:

    LatLng myLaLn = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
    
    CameraPosition camPos = new CameraPosition.Builder().target(myLaLn)
                    .zoom(15)
                    .bearing(45)
                    .tilt(70)
                    .build();
    
     CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
    
     map.animateCamera(camUpd3);
    

    我给你一个简单但完整的例子来显示地图和当前位置:

    (完整项目可在github.com/josuadas/LocationDemo 获得)

    public class MainActivity extends FragmentActivity implements
            GooglePlayServicesClient.ConnectionCallbacks,
            GooglePlayServicesClient.OnConnectionFailedListener {
    
        private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    
        private LocationClient mLocationClient;
        private Location mCurrentLocation;
        private GoogleMap map;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.map);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            setUpMapIfNeeded();
            setUpLocationClientIfNeeded();
            mLocationClient.connect();
        }
    
        private void setUpMapIfNeeded() {
            // Do a null check to confirm that we have not already instantiated the
            // map.
            if (map == null) {
                // Try to obtain the map from the SupportMapFragment.
                map = ((SupportMapFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.map)).getMap();
                // Check if we were successful in obtaining the map.
                if (map == null) {
                    Toast.makeText(this, "Google maps not available",
                            Toast.LENGTH_LONG).show();
                }
            }
        }
    
        private void setUpLocationClientIfNeeded() {
            if (mLocationClient == null) {
                Toast.makeText(getApplicationContext(), "Waiting for location",
                        Toast.LENGTH_SHORT).show();
                mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
                        this); // OnConnectionFailedListener
            }
        }
    
        @Override
        public void onPause() {
            super.onPause();
            if (mLocationClient != null) {
                mLocationClient.disconnect();
            }
        }
    
        /*
         * Called by Location Services when the request to connect the client
         * finishes successfully. At this point, you can request the current
         * location or start periodic updates
         */
        @Override
        public void onConnected(Bundle dataBundle) {
            mCurrentLocation = mLocationClient.getLastLocation();
            if (mCurrentLocation != null) {
                Toast.makeText(getApplicationContext(), "Found!",
                        Toast.LENGTH_SHORT).show();
                centerInLoc();
            }
        }
    
        private void centerInLoc() {
            LatLng myLaLn = new LatLng(mCurrentLocation.getLatitude(),
                    mCurrentLocation.getLongitude());
            CameraPosition camPos = new CameraPosition.Builder().target(myLaLn)
                    .zoom(15).bearing(45).tilt(70).build();
    
            CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
            map.animateCamera(camUpd3);
    
            MarkerOptions markerOpts = new MarkerOptions().position(myLaLn).title(
                    "my Location");
            map.addMarker(markerOpts);
        }
    
        /*
         * Called by Location Services if the connection to the location client
         * drops because of an error.
         */
        @Override
        public void onDisconnected() {
            // Display the connection status
            Toast.makeText(this, "Disconnected. Please re-connect.",
                    Toast.LENGTH_SHORT).show();
        }
    
        /*
         * Called by Location Services if the attempt to Location Services fails.
         */
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            /*
             * Google Play services can resolve some errors it detects. If the error
             * has a resolution, try sending an Intent to start a Google Play
             * services activity that can resolve error.
             */
            if (connectionResult.hasResolution()) {
                try {
                    // Start an Activity that tries to resolve the error
                    connectionResult.startResolutionForResult(this,
                            CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    /*
                     * Thrown if Google Play services canceled the original
                     * PendingIntent
                     */
                } catch (IntentSender.SendIntentException e) {
                    // Log the error
                    e.printStackTrace();
                }
            } else {
                /*
                 * If no resolution is available
                 */
                Log.e("Home", Integer.toString(connectionResult.getErrorCode()));
            }
        }
    }
    

    注意 1:为简单起见,我省略了“检查 Google Play 服务”部分,但应将其添加为一种好的做法。

    注意2:您需要google-play-services_lib 项目并从您的项目中引用它。

    您可以在 android here 中找到有关与谷歌地图交互的所有信息

    【讨论】:

      【解决方案2】:
      mMap.setMyLocationEnabled(true);
      

      此行将在地图右上角显示一个图标,点击该图标后会转到您在地图上的当前位置。

      【讨论】:

        【解决方案3】:

        查看后面的sn-ps代码:

        ...
        MyLocationOverlay myLoc = null;
        MapView myMapView = null;
        GeoPoint mCurrentPoint;
        
        ...
        
        myMapView = (MapView) findViewById(R.id.mapView);
        
            myMapView.setBuiltInZoomControls(true);
            myMapView.setStreetView(true);
        
            mc = myMapView.getController();
            mc.setZoom(17);
            myLoc = new CustomMyLocationOverlay(this, myMapView);
            myLoc.runOnFirstFix(new Runnable() {
                public void run() {
                    if (mCurrentPoint.equals(new GeoPoint(0,0))){
                        mc.animateTo(myLoc.getMyLocation());
                        mCurrentPoint = myLoc.getMyLocation();
                    } 
                }
            });
        
            myMapView.getOverlays().add(myLoc);
            myMapView.postInvalidate();
        
            zoomToMyLocation();
        
            Drawable drawable = this.getResources().getDrawable(R.drawable.target);
            mItemizedoverlay = new MyItemizedOverlay(drawable, this);
        
           // here get your lat, longt as double and put in GeoPoint
        
           mCurrentPoint = new GeoPoint((int)lat,(int)lon);
        
            if (!mCurrentPoint.equals(new GeoPoint(0,0))){
                mc.animateTo(mCurrentPoint);
                setMarker();
            } 
        
        ...
        
        public void zoomToMyLocation() {
            mCurrentPoint = myLoc.getMyLocation();
            if (mCurrentPoint != null) {
                myMapView.getController().animateTo(mCurrentPoint);
                // myMapView.getController().setZoom(10);
            }
        }
        

        ma​​p.xml

        <com.google.android.maps.MapView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true"
        android:enabled="true"
        android:apiKey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"     
        />
        

        希望对你有帮助

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-07
          • 2020-10-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多