谷歌地图标记没有出现?

时间:2015-03-16 08:32:06

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

我正在使用以下代码获取JSONP响应并解析lat和long并在Google地图上输出为Makers。

console.out在控制台中显示正确的lat和long,但是Markers没有出现在地图上。

我做错了什么?

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

       });
     });

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

可能是你的标记超出了地图的范围。目前的界限?添加新标记后,您需要手动更改地图中心或边界,Google地图不会为您执行此操作。

缩放等级12非常窄,所以它绝对是可能的。

相关问题