如何在Google Maps API v3 for android中长按添加标记? Stack Overflow本身就有这方面的答案,但它们适用于Google Maps API v2。
public class advertiserMap extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advertiser_map);
// 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);
}
//for searching for a location
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
答案 0 :(得分:3)
正如@tyczj指出的那样,Android Google Maps API没有v3,所以你可能正在使用v2。
也就是说,要完成你想要的,在你的mMap对象中调用setOnMapLongClickListener,并在mapLongClick里面添加你想要的标记。您应该在onMapReady方法中执行此操作:
public class advertiserMap extends FragmentActivity implements OnMapReadyCallback {
// Declare marker globally
Marker myMarker;
...
@Override
public void onMapReady(GoogleMap googleMap) {
...
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng latLng) {
// First check if myMarker is null
if (myMarker == null) {
// Marker was not set yet. Add marker:
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Your marker title")
.snippet("Your marker snippet"));
} else {
// Marker already exists, just update it's position
myMarker.setPosition(latLng);
}
}
});
}
}
//编辑:
如果你想一次只保留一个标记,你应该在全局活动范围内声明你的标记,然后在onMapLongClick中,如果marker已经存在,而不是创建一个新标记,只需更新它的位置:
JSON
如果这样做,请记住在您的代码中操作之前,请始终检查您的标记是否为NULL。
答案 1 :(得分:0)
大家好,如果大家都在使用mMap.clear(),请删除它。通常,它工作得很好。