在Google地图上PinPoint并在“活动”中显示地图

时间:2016-05-03 09:06:19

标签: android google-maps

我正在使用谷歌地图v2,我是新手,我正在做的是我按下按钮打开地图,事情是我需要在地图上查明某个位置并获取其经度和纬度在另一个具有精确定位位置的活动中再次显示地图。

我对如何操纵谷歌地图以及如何在其他活动中显示它有点困惑,我需要在下面的代码中添加什么?

这是我的地图代码:

public class MapsActivity extends FragmentActivity {

private GoogleMap mMap; // Might be null if Google Play services APK is not available.

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

@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
}

/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #mMap} is not null.
 * <p/>
 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
 * install/update the Google Play services APK on their device.
 * <p/>
 * A user can return to this FragmentActivity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
 * have been completely destroyed during this process (it is likely that it would only be
 * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
 * method in {@link #onResume()} to guarantee that it will be called.
 */
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mMap.setMyLocationEnabled(true);
        Location currentLocation = mMap.getMyLocation();
        if (currentLocation != null) {
            updateLocation(currentLocation);
        } else {
            Log.d(getClass().getName(), "Current location is NULL");
        }
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();
    } else {
        LocationListener locationListener = new MyLocationListener();
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return;
        }
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, locationListener);
        manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 1, locationListener);

        Location locationGPS = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        Location locationNet = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        Location loc;
        long GPSLocationTime = 0;
        if (null != locationGPS) {
            GPSLocationTime = locationGPS.getTime();
        }

        long NetLocationTime = 0;

        if (null != locationNet) {
            NetLocationTime = locationNet.getTime();
        }

        if (0 < GPSLocationTime - NetLocationTime) {
            loc = locationGPS;
        } else {
            loc = locationNet;
        }
        if (loc != null) {
            updateLocation(loc);
        }
        //LatLng sydney = new LatLng(-33.867, 151.206);

    }


}


private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}

private class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {
        updateLocation(loc);
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

}

public void updateLocation(Location loc) {
    Toast.makeText(
            getBaseContext(),
            "Location changed: Lat: " + loc.getLatitude() + " Lng: "
                    + loc.getLongitude(), Toast.LENGTH_SHORT).show();
    String longitude = "Longitude: " + loc.getLongitude();
    Log.v(getClass().getName(), longitude);
    String latitude = "Latitude: " + loc.getLatitude();
    Log.v(getClass().getName(), latitude);

    /*------- To get city name from coordinates -------- */
    String cityName = null;
    Geocoder gcd = new Geocoder(this, Locale.ENGLISH);
    List<Address> addresses;
    /*try {
        addresses = gcd.getFromLocation(loc.getLatitude(),
                loc.getLongitude(), 1);
        if (addresses.size() > 0) {
            Log.d(getClass().getSimpleName(), (addresses.get(0).getLocality() == null ? "Null" : addresses.get(0).getLocality()));
            cityName = addresses.get(0).getLocality();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }*/
    String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
            + cityName;
    Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
    LatLng myLocation = new LatLng(loc.getLatitude(), loc.getLongitude());
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 13));
    mMap.addMarker(new MarkerOptions()
            .title(cityName)
            .snippet("My Location")
            .position(myLocation));
}
}

2 个答案:

答案 0 :(得分:0)

您可以按marker.getPosition()获取标记的LatLongs。只需通过intent extras将这些值发送到您的下一个活动,然后在该活动的地图上再次显示它。

答案 1 :(得分:0)

如果通过精确定位你的意思是点击在地图上添加一个点,那么使用代码:

mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {
                // TODO Auto-generated method stub

                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(point));

                //To Send this point to second mapsActivity
                Intent i=new Intent(MapsActivity.this,MapsActivity1.class);
                Bundle args = new Bundle();
                args.putParcelable("POINT", point);
                i.putExtra("bundle",args);
                startActivity(i);
            }
        });

要创建另一个地图活动,只需右键点击“app”文件夹 - &gt; New-&gt; Google-&gt; Google MapsActivity。 将添加一个新的活动。

在新的MapsActivity的onCreate()内部得到这一点:

Bundle bundle = getIntent().getParcelableExtra("bundle");
LatLng markerPoint = bundle.getParcelable("POINT");

在第二个mapsActivity的setUpMapIfNeeded():

mMap.addMarker(new MarkerOptions().position(markerPoint));
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(markerPoint, 10));

这里10是zoomlevel相应调整它。