我正在使用 osmdroid 编写一个应用程序来显示地图,我想在用户点击地图时为其添加一个标记,实际上我已经能够使用运动事件执行此操作,但这即使在用户放大时也会添加一个标记或出地图我不想要这个。这是我必须添加标记的代码:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int actionType = ev.getAction();
switch (actionType) {
case MotionEvent.ACTION_DOWN:
Projection proj = myOpenMapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int)ev.getX(), (int)ev.getY());
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
List<OverlayItem> anotherOverlayItemArray = new ArrayList<OverlayItem>();
ExtendedOverlayItem mapItem = new ExtendedOverlayItem("", "", new GeoPoint((((double)loc.getLatitudeE6())/1000000), (((double)loc.getLongitudeE6())/1000000)), this);
mapItem.setMarker(this.getResources().getDrawable(R.drawable.marker));
anotherOverlayItemArray.add(mapItem);
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay
= new ItemizedIconOverlay<OverlayItem>(
this, anotherOverlayItemArray, null);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
Toast toast = Toast.makeText(getApplicationContext(), "Longitude: "+ longitude +" Latitude: "+ latitude , Toast.LENGTH_LONG);
toast.show();
}
return super.dispatchTouchEvent(ev);
}
这就是我最终解决它的方法:
Overlay touchOverlay = new Overlay(this){
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = null;
@Override
protected void draw(Canvas arg0, MapView arg1, boolean arg2) {
}
@Override
public boolean onSingleTapConfirmed(final MotionEvent e, final MapView mapView) {
Projection proj = mapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int)e.getX(), (int)e.getY());
longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
ArrayList<OverlayItem> overlayArray = new ArrayList<OverlayItem>();
OverlayItem mapItem = new OverlayItem("", "", new GeoPoint((((double)loc.getLatitudeE6())/1000000), (((double)loc.getLongitudeE6())/1000000)));
mapItem.setMarker(marker);
overlayArray.add(mapItem);
if(anotherItemizedIconOverlay==null){
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
myOpenMapView.invalidate();
}else{
myOpenMapView.getOverlays().remove(anotherItemizedIconOverlay);
myOpenMapView.invalidate();
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
}
dlgThread();
return true;
}
};
myOpenMapView.getOverlays().add(touchOverlay);