简体   繁体   中英

how to get the google map blue point latitude and longitude in android

My objective is to track the user's location and give an alert on reaching marked location. So first I get the location to reach and marked that. Then I get the current location and compare it with marked location. But it is not working. Even I placed the marker at current location. It is not giving the toast message. Here is the code -

public class MainActivity extends FragmentActivity implements LocationListener{
    LocationManager locationManager;
    String provider;
    ToggleButton toggle;

    public static double lat,lang,value1,value2,value3,value4;
    public static String strlat,strlat1;
    public LatLng loc,loc1;
    public  double latitude,longitude; 
    public static String strlang,strlang1 ;
    Location location;

    public LocationManager locationmanager;
        // Google Map
            private GoogleMap googleMap;
            LocationListener Locationlistener;

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

                locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);        

                // Creating an empty criteria object
                Criteria criteria = new Criteria();

                // Getting the name of the provider that meets the criteria
                provider = locationManager.getBestProvider(criteria, false);

               if(provider!=null && !provider.equals("")){

                    // Get the location from the given provider 
                    final Location location = locationManager.getLastKnownLocation(provider);

                    locationManager.requestLocationUpdates(provider, 1000, 1, this);

                    final Handler handler = new Handler();

                    Runnable runnable = new Runnable() {

                        public void run() {
                            if(location!=null){
                                lat = location.getLatitude();
                            lang = location.getLongitude();

                             value3 =Double.parseDouble(new DecimalFormat("##.##").format(lat));
                             value4 =Double.parseDouble(new DecimalFormat("##.##").format(lang));
                             strlat = String.valueOf(value3);
                                strlang = String.valueOf(value4);
                             loc1 =new LatLng(lat, lang);
                            if((value1 == value3) && (value2 == value4))
                            {
                                Toast.makeText(getApplicationContext(), "target reached", Toast.LENGTH_SHORT).show();
                            }
                            else
                                Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();

                        }
                            else{
                            Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
                        }
                            handler.postDelayed(this, 1000);
                        }
                    };

                    handler.post(runnable);
               }

                try {
                    // Loading map
                    initilizeMap();

                    // Changing map type
                    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    // googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                    // googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                    // googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                    // googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

                    // Showing / hiding your current location

                googleMap.setMyLocationEnabled(true);

                    // Enable / Disable zooming controls
                    googleMap.getUiSettings().setZoomControlsEnabled(false);

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

                    // Enable / Disable Compass icon
                    googleMap.getUiSettings().setCompassEnabled(true);

                    // Enable / Disable Rotate gesture
                    googleMap.getUiSettings().setRotateGesturesEnabled(true);

                    // Enable / Disable zooming functionality
                    googleMap.getUiSettings().setZoomGesturesEnabled(true);

                    // create marker
                googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));

                } catch (Exception e) {
                    e.printStackTrace();
                }

                googleMap.setOnMapClickListener(new OnMapClickListener(){
                    public void onMapClick(LatLng point){
                        Toast.makeText(getBaseContext(),
                            point.latitude + ", " + point.longitude,
                            Toast.LENGTH_LONG).show();
                        latitude = point.latitude;
                        longitude = point.longitude;
                        value1 =Double.parseDouble(new DecimalFormat("##.##").format(latitude));
                        value2 =Double.parseDouble(new DecimalFormat("##.##").format(longitude));
                        strlat1 = String.valueOf(value1);
                        strlang1 = String.valueOf(value2);
                        loc=new LatLng(point.latitude, point.longitude);
                        MarkerOptions marker = new MarkerOptions().position(loc).title("Hello Maps ");

                        // adding marker
                        googleMap.addMarker(marker);

                    }
                });
            }

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

            /**
             * function to load map If map is not created it will create it for you
             * */
            private void initilizeMap() {
                if (googleMap == null) {
                    googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                            R.id.map)).getMap();

                    // check if map is created successfully or not
                    if (googleMap == null) {
                        Toast.makeText(getApplicationContext(),
                                "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            }

            /*
             * creating random position around a location for testing purpose only
             */

            @Override
            public void onLocationChanged(Location location) {
                // TODO Auto-generated method stub

            }

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

            }

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

            }

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

            }
    }

There are a few things wrong in your code.

You can't compare coordinates with == because you will never have an exact match for lat/lon coordinates when tracking the device's location. You need to figure out a threshold, and if the device gets within that threshold, then show the alert.

Next, you're not using your onLocationChanged() callback, so you are just looking at the current location one time at app start-up.

Take a look at the code in my other answer here which is about determining if the device is within a circle. This is a similar problem.

So, if you were to make your threshold 10 meters, and consider the target reached if the device is within 10 meters of the target location, you would implement your onLocationChanged() method something like this:

@Override
public void onLocationChanged(Location location) {

    float[] distance = new float[2];

    Location.distanceBetween( location.getLatitude(), location.getLongitude(),
            latitude, longitude, distance);

    if( distance[0] < 10 ){
        //target location reached
        Toast.makeText(getApplicationContext(), "target reached", Toast.LENGTH_SHORT).show();
    }
}

one more daniel.i changed above code now it was working now have some more problem.

1.i tried to set splash screen like in my second.class.i set the above code for google map.it was running for five second while moving from one to another it get stopped

            new Timer().schedule(new TimerTask(){
                public void run() { 
                    Intent intent =  new Intent (MainActivity.this, SecondActivity.class);
                    PendingIntent pendIntent = PendingIntent.getActivity(getBaseContext(), 1000, intent, 0);
                }
            }, 5000);

2.i want set search in google map how to set that i tried that it not working give some idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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