简体   繁体   English

每秒在谷歌地图中添加新标记

[英]Add new marker in google maps every seconds

I created this program which adds a marker at the current position.我创建了这个程序,它在当前的 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: onLocationChanged 方法:

@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.在创建方法中,我只在最后一个和当前长纬度之间的差异大于 10m 时才绘制折线,你可以消除这种情况。

        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在你 class在创建方法之前不要忘记初始化

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) {

}


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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