add marker with Google-Maps-for-Rails

痴心易碎 提交于 2019-12-02 06:32:57

问题


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?


回答1:


If you want to clear markers created by gmaps4rails, use this js function:

Gmaps4Rails.clear_markers();

otherwise, loop through your markers and make marker.setMap(null)

Well, the following function removes all markers and add a new one where user clicks:

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});});
}

Notes:

  • You could use whatever logic you desire in the js code to create only one marker or send it's coordinates through ajax.
  • latitude can be retrieved with: object.latLng.lat(), longitude with: object.latLng.lng()

Another way to add markers is to use the add_marker function described here: https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Dynamic-%28or-Ajax%29-map-refresh



来源:https://stackoverflow.com/questions/5596996/add-marker-with-google-maps-for-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!