2014-04-17 78 views
0

我想在谷歌地图上显示多个标记。我用于每个循环遍历包含经度和纬度的模型列表。但函数被调用,它不显示地图。谷歌地图与多个标记不出现

代码:

 <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> 

回答

0

你有没有尝试这个办法:

$(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代码嵌入藏汉:

http://jsfiddle.net/P2QhE/

+0

检查我的更新d code.i使用类似的方法,但地图没有显示 – Wasfa

+0

哪里是你的div

+0

它上面的脚本tag.i已经更新了我代码 – Wasfa

1

这是行不通的:

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

markerlatLng已经是google.maps.LatLng,其结果将是无效的经纬度。

使用markerlatLng作为center - 属性为options

另外:你应该从循环中分离出来的地图创建。在循环后循环之前创建的地图AMD设置中心:

map.setCenter(markerlatLng); 

此外: 标记的地图属性必须是mapmap_canvas