如何使用地理编码显示地图

时间:2018-09-25 05:33:37

标签: ruby-on-rails google-maps ruby-on-rails-3 google-maps-api-3 google-geocoding-api

我的脚本是

<script type="text/javascript">
 var lat = <%= @town.latitude %>, 
 lon = <%= @town.longitude %>,
 map;
function initialize() {
  var myOptions = {
  center: new google.maps.LatLng(lat, lon)
};
   map = new google.maps.Map(document.getElementById('map_canvas'),
    myOptions);
}
 google.maps.event.addDomListener(window, 'load', initialize);

  <script type="text/javascript" src="//maps.google.com/maps?file=api&  v=2.x&key="My api key"&libraries=places"></script>

我可以获取经度和纬度,但是我的地图无法加载。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

这里是工作示例,您可以根据需要对其进行更新(删除不需要的部分并添加rails变量代替静态经纬度):

    <!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: <%= @lat %>, lng: <%= @long %>},
          zoom: 8
        });
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=yourkey&callback=initMap"
    async defer></script>
  </body>
</html>

这是我的示例Home控制器索引操作代码:

class HomeController < ApplicationController
  def index
    @lat = "43.8563"
    @long = "18.4131"
  end
end

enter image description here