[英]Javascript: adding markers on google maps using json file
I am trying to add markers of bus stops for Singapore on using google maps. 我正在尝试使用Google地图添加新加坡公交车站的标记。 My code: 我的代码:
<!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? key=AIzaSyB_rFf5Ow4UXIxmXtRXMvVbfIinBSWDc7o&sensor=false">
</script>
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(1.290270,103.851959 ),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery- latest.min.js"></script>
</head>
<body onload="initialize()" >
<div id="map_canvas" style="width:100%; height:100%"></div>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("bus-stops.json", function(json1) {
$.each(json1, function(key, data) {
var latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
title: data.name
});
marker.setMap(map);
});
});
});
</script>
I have placed bus-stops.json in the same folder as this file. 我已将bus-stops.json与此文件放在同一文件夹中。 The code is only displaying the google map without the markers.The data looks like this: 该代码仅显示不带标记的google map。数据如下所示:
[{"no":"10009","lat":"1.28210155945393","lng":"103.81722480263163","name":"Bt Merah Int"},{"no":"10011","lat":"1.2777380589964","lng":"103.83749709165197","name":"Opp New Bridge Rd Ter"}]
Please tell me where am I going wrong. 请告诉我我要去哪里错了。 Thanks 谢谢
Most likely a timing problem. 最有可能是时间问题。 Call the asynchronous $.getJSON
function from the initialize function, or deal with the case where the map isn't initialized when it runs. 从initialize函数调用异步$.getJSON
函数,或处理map在运行时未初始化的情况。
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(1.290270, 103.851959),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
$.getJSON("bus-stops.json", function(json1) {
$.each(json1, function(key, data) {
var latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
title: data.name
});
marker.setMap(map);
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.