简体   繁体   English

从外部json向Google地图添加标记?

[英]Add markers to google maps from external json?

I have to add multiple markers to a google map, but the data is in an external json file. 我必须向Google地图添加多个标记,但数据位于外部json文件中。

At the moment I'm trying to run it using jquery getJSON. 目前,我正在尝试使用jquery getJSON运行它。 But it will not work at all, and console returns no errors! 但是它根本无法工作,并且控制台不会返回任何错误!

    google.maps.event.addDomListener(window, 'load', initialize);



    function initialize() {

        var map_canvas = document.getElementById('map1'); 


        var map_options = {
            center: new google.maps.LatLng(44.5403, -78.5463), 
            zoom: 8, 
            mapTypeId: google.maps.MapTypeId.ROADMAP 
        };

        var map = new google.maps.Map(map_canvas, map_options); 



        $.getJSON('map_points.json', function(data) { 
            $.each( data.points, function(i, value) {
            var myLatlng =  new google.maps.LatLng(value.lat, value.lon);
            alert(myLatlng);
            var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title:"Hello World!"
        });

            });


    });


    } //End initialize()

And the Json 还有杰森

{

"points":[
    {"id":1,"lat":44.5403,"lon":-79.5463},
    {"id":2,"lat":45.5403,"lon":-78.5463},
    {"id":3,"lat":45.5403,"lon":-76.5463},
    {"id":4,"lat":45.5403,"lon":-77.5463}
]


}

I've just tested below code & It's working. 我刚刚测试了下面的代码,并且可以正常工作。 Just try : 你试一试 :

<html>
<head>
<title>Eg. Google Maps Marker using External JSON</title>
<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://code.jquery.com/jquery-latest.min.js"></script> 
<script type="text/javascript" src = "http://maps.google.com/maps/api/js?sensor=false">

</script>
<script type="text/javascript">
function initialize() {

var mapOptions = {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

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

  $.getJSON('map_points.json', function(data) { 
            $.each( data.points, function(i, value) {

                var myLatlng = new google.maps.LatLng(value.lat, value.lon);
                alert(myLatlng);
                var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: "text "+value.lon
                });

            });
});


}

</script>
</head>
<body onload="initialize()">
<form id="form1" runat="server">
<div id="map_canvas" style="width: 500px; height: 400px"></div>
</form>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM