首页 > 解决方案 > 如何通过单击按钮将标记添加到 GoogleMap

问题描述

我想GoogleMap使用按钮将我当前位置的标记添加到地图(检查点)。这就是我到目前为止所拥有的。可能一个问题是 mMap 是在onMapReady()函数内部初始化的,但是如何解决呢?

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);


}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
}

public void buttonClicked(View view) {
    //Instantiate a Builder object
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    //Create an intent for the activity
    Intent notifyIntent = new Intent(this, MainActivity.class);
    //set the activity to start in a new, empty task
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    //Create pendingIntent
    PendingIntent notifyPendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    //Put pendingIntent into the notification builder
    builder.setContentIntent(notifyPendingIntent);
    //Add components
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.common_google_signin_btn_icon_dark));
    builder.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark);
    builder.setContentTitle("Content Title");
    builder.setContentText("Content Text");


    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(1234, builder.build());
}

public void setStartLocation(View view) {

}

public void setWaypoint(View view) {
    //place marker
    //remove previous marker
    //measure distance from starting position
    //add to total milage
    //time calculations too
}

public void setCheckpoint(View view) {
    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    mFusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if (location != null) {
                LatLng position = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.addMarker(new MarkerOptions()
                        .position(position)
                        .title("Checkpoint"));
            }
        }
    });
}

}

标签: androidgoogle-maps

解决方案


private GoogleMap mMap;

@Nullable
@Override
public View onCreateView() {
    // code
    startMap();
    // code
}

private void startMap() {
    // start map here
}

@Override
public void onMapReady(GoogleMap googleMap) {
    // sometimes this function return null
    if(googleMap == null) return;
    mMap = googleMap;
}

然后:

public void setCheckpoint(View view) {
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    return;
}
mFusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
    @Override
    public void onSuccess(Location location) {
        if (location != null) {
            LatLng position = new LatLng(location.getLatitude(), location.getLongitude());
            if(mMap != null) {
                 mMap.addMarker(new MarkerOptions()
                    .position(position)
                    .title("Checkpoint"));
            }
        }
    }
});

}


推荐阅读