简体   繁体   中英

Add new marker in google maps every seconds

I created this program which adds a marker at the current position.

I tried to solve the problem with a handler and a broadcast receiver but the code does not work.

It does not show a new marker, when the location is changed.

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {


    GoogleMap mapAPI;
    SupportMapFragment mapFragment;
    double lat, lng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapAPI);
        displayMap();
    }

    private void displayMap() {

        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mapAPI = googleMap;
        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;
        }
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));


        lat = location.getLatitude();
        lng = location.getLongitude();
        LatLng Me = new LatLng(lat, lng);
        mapAPI.addMarker(new MarkerOptions().position(Me).title("Me"));
        mapAPI.moveCamera(CameraUpdateFactory.newLatLng(Me));
    }
}

You are getting last know location. You should use location update listener.

boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
locationManager.requestLocationUpdates(isNetworkEnabled ? LocationManager.NETWORK_PROVIDER : LocationManager.GPS_PROVIDER, 10, 10, this);

onLocationChanged method:

@Override
public void onLocationChanged(Location location) {
    lat = location.getLatitude();
    lng = location.getLongitude();
    LatLng Me = new LatLng(lat, lng);
    mapAPI.addMarker(new MarkerOptions().position(Me).title("Me"));
    mapAPI.moveCamera(CameraUpdateFactory.newLatLng(Me));
}

here is the code im using, im drawing polyline instead of marker on location change of user,,

   //call this fucntion when you want to add marker to user current loaction every 
   //second
    private void realLocation (){
    if(liveloction){

        locationrequestfunct(); //first we need to create request
        if(mLocationPermissionGranted){
            fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
            mMap.setMyLocationEnabled(true);
        }

    }

}

private void locationrequestfunct(){
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(30000); //you can set the time interval here
    mLocationRequest.setFastestInterval(10000);//im getting updat every10s
   //1000 = 1second ..set your fastest interval to 1000 ,
    mLocationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
//set the priority to high as you want to add marker every second

}

And in on create method, i ghave my on logic im only drawing the poly line when the difference between last and current long lat is gereater than 10m, you can reomve this condition.

        mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {

            if(liveloction) {
                List<Location> mlocationlist = locationResult.getLocations();
                if(mlocationlist.size() >0){

                    Location location_re = mlocationlist.get(mlocationlist.size() - 1);
                    latLngliveold = latLnglive;
                    latLnglive = new LatLng(location_re.getLatitude(), location_re.getLongitude());

                    if(latLngliveold != null){
                        Location.distanceBetween(latLngliveold.latitude,latLngliveold.longitude,
                                latLnglive.latitude,latLnglive.longitude,results);
                        if(results[0]>10){

                            points.add(latLnglive);
                            MarkerOptions markerOptions = new MarkerOptions().position(latLnglive)
                                    .title(String.valueOf(points.size()));
                            marker = mMap.addMarker(markerOptions);
                            marker.setIcon(BitmapDescriptorFactory.fromBitmap(placeh_blue));
                            marker.setDraggable(false);

                            mMap.animateCamera(CameraUpdateFactory.newLatLng(latLnglive));

                            drawploygon(points);
                            p =SphericalUtil.computeLength(points);
                            distanceconver(p,false);
                            updatedistancedetails(points);
                            area = SphericalUtil.computeArea(points);
                            areaconvert(area);

                        }

                    }else {

                        latLngliveold = latLnglive;
                        points.add(latLnglive);
                        MarkerOptions markerOptions = new MarkerOptions().position(latLnglive)
                                .title(String.valueOf(points.size()));
                        marker = mMap.addMarker(markerOptions);
                        marker.setIcon(BitmapDescriptorFactory.fromBitmap(placeh_blue));
                        marker.setDraggable(false);

                        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLnglive));

                        drawploygon(points);
                        p =SphericalUtil.computeLength(points);
                        distanceconver(p,false);
                        updatedistancedetails(points);
                        area = SphericalUtil.computeArea(points);
                        areaconvert(area);

                    }

                }
            }

        }
    };

And in you class before on create method dont forgot to initialize

LocationCallback mLocationCallback;
package com.example.googlemaps;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {

GoogleMap mapAPI;
SupportMapFragment mapFragment;
double lat, lng;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapAPI);
    displayMap();
}

private void displayMap() {

    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mapAPI = googleMap;
    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;
    }
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 10, this);

}

@Override
public void onPointerCaptureChanged(boolean hasCapture) {

}

@Override
public void onLocationChanged(Location location) {
    lat = location.getLatitude();
    lng = location.getLongitude();
    LatLng Me = new LatLng(lat, lng);
    mapAPI.addMarker(new MarkerOptions().position(Me).title("Me"));
    mapAPI.moveCamera(CameraUpdateFactory.newLatLng(Me));
}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}


}

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