【问题标题】:How to display map using geocode如何使用地理编码显示地图
【发布时间】:2018-09-25 05:33:37
【问题描述】:

我的脚本是

<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>

我可以获取纬度和经度,但我的地图没有加载。谁能帮我解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    这是一个工作示例,您可以根据需要对其进行更新(删除不需要的内容并添加 rails 变量来代替静态 lat long):

        <!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
    

    【讨论】:

    • 谢谢@Nezir。但我的地图没有显示
    • 在控制台中没有显示任何错误。我更改了以下 center: {lat: @town.latitude, lng: @town.longitude}
    • 你能创建一个简单的 index.html 文件并粘贴上面的代码,然后添加你的 api 密钥并尝试在浏览器中打开那个 index.html 文件吗?
    • 是的,我已经做到了。它正在工作!!!。但我的问题是我想动态加载 lat 和 lang。我们该怎么做?
    • 更新代码以使用 rails 变量 lat 和 long 立即检查此示例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多