google map with multiple markers is not appearing

若如初见. 提交于 2019-12-19 11:56:45

问题


I want to display multiple markers on google map.I am using for each loop to iterate over the model list that contains latitude and longitude.But function is called and it does not show a map.

code:

      <div id="map_canvas" style="width: 80%; height: 80%">  </div>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
     </script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?
       sensor=false"></script>
      <script type="text/javascript">
$(document).ready(function () {
    alert("working");
    var map;
    var locations = [];

    var options = {
        zoom: 14,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map($('#map_canvas')[0], options);


    @* This is the razor loop *@
    @foreach (var item in Model) {
    <text>
    locations.push(item.latitude, item.longitude);

    </text>
     }
    var i;
    for (i = 0; i <= locations.length; i++) {
        var latlng = new google.maps.LatLng(locations[i][0], locations[i][1]);

        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
        });

    }

});
 </script>

回答1:


Have you try this :

$(document).ready(function () {
var map;
var elevator;
var myOptions = {
    zoom: 1,
    center: new google.maps.LatLng(0, 0),
    mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);

var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];

for (var x = 0; x < addresses.length; x++) {
    $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
        var p = data.results[0].geometry.location
        var latlng = new google.maps.LatLng(p.lat, p.lng);
        new google.maps.Marker({
            position: latlng,
            map: map
        });

    });
}

});

Javascript code embedded aswell:

http://jsfiddle.net/P2QhE/




回答2:


This will not work:

 var latlng = new google.maps.LatLng(markerlatLng);

markerlatLng already is a google.maps.LatLng, the result will be an invalid LatLng.

Use markerlatLng as center-property for options

Furthermore: you should separate the map-creation from the loop. Create the map before the loop amd set the center after the loop:

map.setCenter(markerlatLng);

Additionally: the map-property of the markers has to be map not map_canvas



来源:https://stackoverflow.com/questions/23130484/google-map-with-multiple-markers-is-not-appearing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!