我有一个jquery函数,它通过php文件从数据库中检索纬度和经度。在同一个js文件中,我有一个将标记放在Google地图上的功能。我想使用第一个函数返回的json(lat和long),在Google maps中添加标记函数。目前在我的代码下面,.. json数据只显示在空div中。有没有办法在函数之间访问json数据,还是可以以某种方式组合这两个函数?
// Google Map
var map;
// markers for map
var markers = [];
// initialize the map
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.09024, lng: -95.712891},
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 4
});
}
// add markers
function addMarker(data) {
// get lat and long from data(json object)
var myLatlng = new google.maps.LatLng(parseFloat(data.latitude), parseFloat(data.longitude));
// custom marker image
//var image = "../img/infoblue.png";
// new marker
var marker = new MarkerWithLabel({
position: myLatlng,
map: map,
labelClass: "label",
labelContent: data.name,
labelAnchor: new google.maps.Point(20,0),
});
// add marker to array
markers.push(marker);
}
// this function gets json and then displays in a div on an html page
$(document).ready(function(){
$('.airport_form').submit(function(){
// show that something is loading
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: "post",
dataType: "json",
url: "response.php",
data: $(this).serialize()
})
.done(function(data){
// show the response
$('#response').html("Name -> " + data.name + "<br>" + " Iata code -> " + data.iata + "<br>" + " Lat. -> " + data.latitude + "<br>" + " Longitude -> " + data.longitude);
})
.fail(function() {
// just in case posting the form fails
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
答案 0 :(得分:1)
您可以将addMarker
功能添加到done
功能中,如此...
.done(function(data){
// add marker from data
addMarker(data);
// show the response
$('#response').html("Name -> " + data.name + "<br>" + " Iata code -> " + data.iata + "<br>" + " Lat. -> " + data.latitude + "<br>" + " Longitude -> " + data.longitude);
})