简体   繁体   English

使用Google地图和Ruby添加标记

[英]Adding Markers with Google Maps and Ruby

I am on ruby and set a map on the page. 我在ruby上并在页面上设置了一张地图。 I can add markers upon initialization, but what i would like is to loop through my @events and find the longitude and latitude fields and do something like this 我可以在初始化时添加标记,但我想要的是遍历我的@events并找到经度和纬度字段并执行类似这样的操作

<% @event.each do |event|%>
  <script type="text/javascript">
    var long = <%= event.longitude %>;
    var lati = <%= event.latitude %>;
    addMarker(long, lati);
  </script>
<% end %>

I am not familiar with google api, but was hoping if it was possible. 我不熟悉谷歌api,但希望是否有可能。

Here what I have in term of building the map api 这就是我在构建地图api方面所拥有的

function initialize() 
{
    var lat, lon, map, myOptions;
    //check if user has geo feature
    if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(
    //get position

    function(position){
        lat = position.coords.latitude;
        lon = position.coords.longitude;

        //init map
        myOptions = {
           center: new google.maps.LatLng(lat, lon),
           zoom: 8,
           mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"),
            myOptions);
            var myLatlng = new google.maps.LatLng(46.4352,-80.9455);
    var marker = new google.maps.Marker({
        position: myLatlng,
        title:"Hello World!"
    });
    // To add the marker to the map, call setMap();
    marker.setMap(map);
    },
    // if there was an error
    function(error){
        alert('ouch');
    });
    }
    //case the users browser doesn't support geolocations
    else 
    {
        alert("Your browser doesn't support geolocations, please consider downloading Google Chrome");
    }
}

Here's my suggestion: 这是我的建议:

<script type="text/javascript">

  function addMarker(lat, lng) {
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(lat, lng),
      map: map
    });
  }

  <% @events.each do |event| %>
    addMarker(<%= event.latitude %>, <%= event.longitude %>);
  <% end %>

</script>

Create an addMarker function (if it doesn't already exist) that takes two arguments — latitude and longitude — and adds a corresponding marker to the existing map. 创建一个addMarker函数(如果它尚不存在),它接受两个参数 - 纬度和经度 - 并将相应的标记添加到现有地图。 Then, you can use Ruby to create one call to addMarker per @event . 然后,你可以使用Ruby创建一个呼叫addMarker@event

There are ways to optimize this further. 有进一步优化的方法。 For example, you could have a separate Ruby script that outputs the coordinates as JSON, and use asynchronous HTTP request (aka Ajax) to load the coordinates into an array at runtime, which you could then use to populate the map. 例如,您可以使用单独的Ruby脚本将坐标输出为JSON,并使用异步HTTP请求(也称为Ajax)在运行时将坐标加载到数组中,然后您可以使用它来填充地图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM