【问题标题】:Google Maps Markers not appearing?谷歌地图标记没有出现?
【发布时间】:2015-05-18 07:25:44
【问题描述】:

我正在使用下面的代码来获取 JSONP 响应并解析出 lat 和 long 并在谷歌地图上作为 Maker 输出。

console.out 在控制台中显示正确的纬度和经度,但是标记没有出现在地图上。

我做错了什么?

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map_canvas { height: 100% }
    </style>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true">
    </script>
    <script type="text/javascript">
      var map;
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(-36.8, 174.6),
          zoom: 12,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
      }
    </script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>    
  </head>
  <body>
    <div id="map_canvas" style="width:100%; height:100%"></div>
    <script>
     $(document).ready(function() {
        jQuery.ajax({
            type: "GET",
            url: 'http://api.at.govt.nz/v1/public/realtime/vehiclelocations?api_key=<APIKEYHERE>',
            dataType: "jsonp",
            cache: false,
            crossDomain: true,
            processData: true,

            success: function (data) {
                //alert(JSON.stringify(data));
                var iconBase = 'images/';
                map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);

                $.each(data.response.entity, function(key, data) {
                    var latLng = new google.maps.LatLng(data.vehicle.position.latitude,data.vehicle.position.longitude); 
                    console.log(latLng);
                    // Creating a marker and putting it on the map
                    var marker = new google.maps.Marker({
                        position: latLng,
                        map: map,
                        //icon: iconBase + 'bus2.png'
                    });
                });
              initialize();
            },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
         alert("There is a problem");
        }

       });
     });

【问题讨论】:

  • AJAX 查询返回的数据是什么样的?

标签: ajax json google-maps jsonp google-maps-markers


【解决方案1】:

会不会是您的标记超出了地图的当前范围?添加新标记后,您需要手动更改地图中心或边界,谷歌地图不会为您完成。

12 级缩放非常窄,所以绝对有可能。

【讨论】:

    【解决方案2】:

    您在 ajax-callback 和 onload 中创建了两次地图。

    删除onload-listener 并在ajax-callback 中调用initialize() 而不是

    map = new google.maps.Map(document.getElementById("map_canvas"),
                mapOptions);
    

    【讨论】:

    • 谢谢博士。今晚我会测试并接受答案。
    • 不幸的是,这不起作用。我已根据您的建议更新了代码。
    • 您更新后的代码代码仍然会在 $.each 之前和之后创建两次地图
    猜你喜欢
    • 1970-01-01
    • 2020-03-09
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 2011-04-17
    • 2018-09-26
    • 2020-08-13
    相关资源
    最近更新 更多