更新地图标记位置 onLocationChanged() 不起作用

update map marker position onLocationChanged() is not working

我正在制作 google 地图,我想在 onLocationChanged() 方法中用户位置发生变化时更改地图标记位置。我在 Stack overflow 上尝试了很多可用的解决方案,但 none 适合我。 我试过 和许多其他人但都失败了。

我没有找到更新标记的正确代码方法。

非常感谢!

here's my MapsActivity

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, TaskLoadedCallback {

    static Marker now;
    public static GoogleMap mMap;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_track_order);
        Log.i("map", "create");

        SupportMapFragment mapFragment1 = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        if (mapFragment1 != null) {
            mapFragment1.getMapAsync(this);
        }

        initViews();
        setToolbar()
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

 mMap = googleMap;
        if (!runtime_permissions()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Intent serviceIntent = new Intent(getApplicationContext(), MyService.class);
                ContextCompat.startForegroundService(getApplicationContext(), serviceIntent);
            } else {
                startService(new Intent(getApplicationContext(), MyService.class));
            }
        }


        mMap.addMarker(place1);
        mMap.addMarker(place2);

        CameraPosition googlePlex = CameraPosition.builder()
                .target(new LatLng(31.527653,74.455632))
                .zoom(7)
                .bearing(0)
                .tilt(45)
                .build();

        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 5000, null);

}

here's my Service class

public class MyService  extends Service {


    public static LocationListener listener;
    public static LocationManager locationManager;
    private String locationAddress;

    @Override
    public void onCreate() {
        super.onCreate();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            startMyOwnForeground();
        else
            startForeground(1, new Notification());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                String userAddress = address(latitude, longitude);

                 /*not working*/
                Marker myMarker = null;
                if(myMarker == null){
                  //  marker = mMap.addMarker(options);
                }
                else {
                    marker.setPosition(new LatLng(location.getLatitude(),location.getLongitude()));
                }

            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {
                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }

        };

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

        //noinspection MissingPermission
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, CommonObjects.DELAY_LOCATION_UPDATE, 0, listener);

        return START_STICKY;
    }
}

请在locationChangedMethod中添加

 MarkerOptions pin_01_markerOptions = new MarkerOptions();
                    pin_01_markerOptions.position(currentLatLng);
                    pin_01_markerOptions.icon(BitmapDescriptorFactory.fromBitmap(pin_01_marker));

                mMap.addMarker(pin_01_markerOptions);




 LatLng currentLatLng = new LatLng(location.getLatitude(),location.getLongitude());

                CameraUpdate update = CameraUpdateFactory.newLatLngZoom(currentLatLng,
                        15);
                mMap.moveCamera(update);

经过深思熟虑,我发现无法在 onLocationChanged() 中更新地图标记。相反,我必须更新我的标记 onMapReady() 方法。

通过从我的 Service class 方法发送广播到 onMapReady() 方法,我得到了问题的解决方案 更新地图标记位置 onLocationChanged()

更新代码:

MyService.java

public class MyService  extends Service {

     ...   

    @Override
    public void onCreate() {
        super.onCreate();

      ...
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                String userAddress = address(latitude, longitude);

                 /*sending broadcast*/
                Intent i = new Intent("location_update");
                i.putExtra("latitude", latitude);
                i.putExtra("longitude", longitude);
                i.putExtra("address", userAddress);
                sendBroadcast(i);

            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {
                ...
            }

        };

      ...
        return START_STICKY;
    }
}

MapsActivity.java

此外,我在 onCreate() 开始 Service 而不是 onMapReady()

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, TaskLoadedCallback {

    ...

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

       ...

       /* staring service from here*/
       if (!runtime_permissions()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Intent serviceIntent = new Intent(getApplicationContext(), MyService.class);
                ContextCompat.startForegroundService(getApplicationContext(), serviceIntent);
            } else {
                startService(new Intent(getApplicationContext(), MyService.class));
            }
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;
        place2 = new MarkerOptions().position(destination).title("Isl");
        mMap.addMarker(place2);

        /*receiving broadcast*/
        if (broadcastReceiver == null) {
            broadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {

                    lat = (double) intent.getExtras().get("latitude");
                    lng = (double) intent.getExtras().get("longitude");
                    String  userAddress = (String) intent.getExtras().get("address");

                    place1 = new MarkerOptions().position(new LatLng(lat, lng)).title("Lahore");
                    mMap.addMarker(place1);
                }
            };
        }
        registerReceiver(broadcastReceiver, new IntentFilter("location_update"));


        CameraPosition googlePlex = CameraPosition.builder()
                .target(new LatLng(31.527653,74.455632))
                .zoom(7)
                .bearing(0)
                .tilt(45)
                .build();

        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 5000, null);
      }
}