合并将标记添加到地图的方法

时间:2014-03-10 18:23:02

标签: android google-maps-markers google-maps-api-2

在我的应用程序中,我使用if / else语句,onMapLongClick将更新标记的位置(如果存在),或者创建标记(如果不存在)。我想将SearchView与Google Places API一起使用,因此我使用了一个教程,我通过Stack Overflow上的帖子阅读。它利用Google Places API的搜索结果来创建标记。太好了!但是,它使用自己的addMarker。所以,我希望有人能够让我朝着正确的方向前进,这样我就可以将Google Places API生成的结果与我添加标记的方法联系起来。 (教导男人钓鱼,不要给男人钓鱼。)

我的方法:

@Override
public void onMapLongClick(LatLng point) {
 if(marker != null){ //if marker exists (not null or whatever)
     marker.setPosition(point);
 }
 else{
    marker = map.addMarker(new MarkerOptions()
    .position(point)
    .title("Your Destination")
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
    .draggable(true));
}
    if(marker!=null){
     CameraPosition cameraPosition = new CameraPosition.Builder()
     .target(point)
     .zoom(10)
     .build();
     map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}

Google-Places-API结果的教程方法:

private void showLocations(Cursor c){
    MarkerOptions markerOptions = null;
    LatLng position = null;
    map.clear();
    while(c.moveToNext()){
        markerOptions = new MarkerOptions();
        position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2)));
        markerOptions.position(position);
        markerOptions.title(c.getString(0));
        map.addMarker(markerOptions);
    }
    if(position!=null){
        CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
        map.animateCamera(cameraPosition);
    }
}

1 个答案:

答案 0 :(得分:0)

可能有一种更好的方法可以做到这一点,但在稍微修改一下后,我能够将我的方法的代码循环到教程方法中,它看起来像这样:

private void showLocations(Cursor c){

    LatLng position = null;
    while(c.moveToNext()){
        position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2)));
        if(marker != null){ //if marker exists (not null)
         marker.setPosition(position);
     }
     else{
        marker = map.addMarker(new MarkerOptions()
        .position(position)
        .title("Your Destination")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
        .draggable(true));
    }
    if(position!=null){
        CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
        map.animateCamera(cameraPosition);
    }
    }
}

现在,无论用户是长时间点击地图上的某个位置,还是从给定的搜索结果中选择一个位置,都只会在地图上显示一个用户设置标记。嗬!