2

I was playing with https://github.com/apneadiving/Google-Maps-for-Rails and i'd like to clear all the marker on a map and add a new one at the position clicked by the user on the map, I added the following code in my page

<script type="text/javascript" charset="utf-8">
function gmaps4rails_callback() {
   google.maps.event.addListener(Gmaps4Rails.map, 'click', function(object){ 
      alert(object.latLng);
   });
</script>

And in this way i can see an alert with the lat and long value, now how can i delete the old markers and create a new marker and place it on the map?

4

1 に答える 1

3

によって作成されたマーカーをクリアする場合はgmaps4rails、次のjs関数を使用します。

Gmaps4Rails.clear_markers();

それ以外の場合は、マーカーをループして作成しますmarker.setMap(null)

次の関数は、すべてのマーカーを削除し、ユーザーがクリックする場所に新しいマーカーを追加します。

var marker = null;
function gmaps4rails_callback() {
   Gmaps4Rails.clear_markers();
   if (marker != null) { marker.setMap(null); }
   google.maps.event.addListener(Gmaps4Rails.map, 'click', function(object){ marker = new google.maps.Marker({position: object.latLng, map: Gmaps4Rails.map});});
}

ノート:

  • jsコードで必要なロジックを使用して、マーカーを1つだけ作成するか、その座標をajaxを介して送信できます。
  • 緯度は次のように取得できます。object.latLng.lat()経度は次のように取得できます。object.latLng.lng()

マーカーを追加する別の方法は、add_markerここで説明されている関数を使用することです:https ://github.com/apneadiving/Google-Maps-for-Rails/wiki/Dynamic-%28or-Ajax%29-map-refresh

于 2011-04-08T19:02:47.283 に答える