google map with multiple markers is not appearing

2020-03-31 06:46发布

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>

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-03-31 07:02

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/

查看更多
再贱就再见
3楼-- · 2020-03-31 07:20

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

查看更多
登录 后发表回答