-1
我正在使用谷歌地圖在腳本上繪製地圖上的多個位置。 我參考了this腳本,它有一個靜態json位置來繪製。
因爲我需要首先獲得位置的緯度,所以我提到this要點。 我試圖合併2個腳本來獲得多個繪圖,但是,我正面臨循環中的問題。該功能目前只繪製了最後一個位置,並且 爲前兩個,它不稱爲getLocation
功能。通過獲取緯度和經度在地圖上繪製多個位置
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
var markers = [
{
"title": 'Juhu Beach',
"description": 'Juhu Beach is one of favourite tourist attractions situated in Mumbai.'
},
{
"title": 'Jijamata Udyan',
"description": 'Jijamata Udyan is situated near Byculla station is famous as Mumbai (Bombay) Zoo.'
},
{
"title": 'Sanjay Gandhi National Park',
"description": 'Sanjay Gandhi National Park is a large protected area in the northern part of Mumbai city.'
}
];
window.onload = function() {
LoadMap();
}
var json = {};
var latitude;
var longitude;
var getLocation = function(address,callback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
json = {
'lat':latitude,
'lng':longitude
}
if(typeof callback === 'function'){
callback(json);
}
}
});
}
function LoadMap() {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
//Create and open InfoWindow.
var infoWindow = new google.maps.InfoWindow();
var data;
var myLatlng;
var marker;
for (var i = 0; i < markers.length; i++) {
console.log(i);
data = markers[i];
console.log('object',data.description);
getLocation(data.description,function(result){
myLatlng = new google.maps.LatLng(result.lat, result.lng);
marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
//Attach click event to the marker.
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
//Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
infoWindow.setContent("<div style = 'width:200px;min-height:40px'>" + data.description + "</div>");
infoWindow.open(map, marker);
});
})(marker, data);
})
}
}
我摸不清哪裏回調打破了第2 loops.Any幫助將appreaciated。
我想,爲什麼我需要的'getLocation'函數將返回LAT long.Hence我從JSON取出lat和長參數,以獲取經緯度長動態是。 – KillABug
我已經通過保持getLocation函數編輯了我的答案。請立即檢查。 –
我會測試並更新它是否有效。謝謝 – KillABug