Google地图标记未出现在$ .getJSON Javascript中

时间:2014-07-31 06:27:38

标签: javascript json google-maps-markers

我正在阅读JSON文件,将我的纬度和经度绘制到Google地图上。我尝试过使用不同的方法但没有出现。对于这种方法,地图显示但标记不存在。

//this is my json file: out1copy.json
[{
  "GPSLatitude": "1.306279",
  "GPSLongitude": "103.904783",
  "Title": "Joo Chiat Road"
},
{
  "GPSLatitude": "1.343176",
  "GPSLongitude": "103.851983",
  "Title": "Braddell Road"
},
{
  "GPSLatitude": "1.318105",
  "GPSLongitude": "103.766597",
  "Title": "Clementi Avenue"
},
{
  "GPSLatitude": "1.427895",
  "GPSLongitude": "103.837806",
  "Title": "Yishun Central"
}]

这是我的html文件:

<!DOCTYPE html> 
<html>
<head>
<title>Try (Markers gone)</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
  html, body, #map-canvas {
    height: 100%;
    margin: 0px;
    padding: 0px
  }
</style>
<body>
<div id="map-canvas"></div>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

var map;
var myLatlng = new google.maps.LatLng(1.3667, 103.8);
var mapOptions = {
        zoom: 11,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
}

map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

$.getJSON('out1copy.json', function(data){ 
    $.each(data.markers, function(i, item) {
        var latlng = new google.maps.LatLng(item.GPSLatitude,item.GPSLongitude);
        new google.maps.Marker({
            position: latlng,
            map: map
        });
    });        
});

</script>
</head>
</html>

可能出错的地方?

1 个答案:

答案 0 :(得分:1)

在运行地图功能之前,您需要等待dom加载:

google.maps.event.addDomListener(window, 'load', function() {
    var map;
    var myLatlng = new google.maps.LatLng(1.3667, 103.8);
    var mapOptions = {
            zoom: 11,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    $.getJSON('out1copy.json', function(data){ 
        $.each(data.markers, function(i, item) {
            var latlng = new google.maps.LatLng(item.GPSLatitude,item.GPSLongitude);
            new google.maps.Marker({
                position: latlng,
                map: map
            });
        });        
    });

});