我有一个google地图API工作得很好,但有时它不会产生结果,我只是得到可怕的灰色框(取决于输入的是什么地址)。
这是我的代码:
var map;
var geocoder;
var markers = new Array();
var firstLoc;
function myGeocodeFirst() {
geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': "<?php echo stripslashes($centre_name) . ", " . preg_replace('#\s+#',',',trim($address)); ?>" },
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
firstLoc = results[0].geometry.location;
map = new google.maps.Map(document.getElementById("map_canvas"),
{
center: firstLoc,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: firstLoc,
animation: google.maps.Animation.DROP,
map: map,
title: '<?php echo stripslashes($centre_name); ?>'
});
var contentString = '<div id="content">'+
'<span id="firstHeading" class="firstHeading"><?php echo stripslashes($centre_name); ?></span>'+
'</div>';
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
var infowindow = new google.maps.InfoWindow({
content: contentString
});
}
}
);
}
如果第一个地址不提供地理位置,我希望尝试第二个地址。这可能吗?我根本无法在网上找到任何东西。
我尝试了各种各样的if / elses,但它似乎只是使代码崩溃
答案 0 :(得分:0)
你只是检查一下&#34; OK&#34;以外的其他东西的返回状态。
查看api页面
https://developers.google.com/maps/documentation/geocoding/#StatusCodes
答案 1 :(得分:0)
如果初始地址因ZERO_RESULTS而失败,这将对“New York,NY”进行地理编码。
var addresses = ["<?php echo stripslashes($centre_name) . ", " . preg_replace('#\s+#',',',trim($address)); ?>", "New York, NY"]
function myGeocodeFirst() {
geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': addresses[0] }, geocoderCallback);
}
function geocoderCallback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
firstLoc = results[0].geometry.location;
map = new google.maps.Map(document.getElementById("map_canvas"),
{
center: firstLoc,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: firstLoc,
animation: google.maps.Animation.DROP,
map: map,
title: '<?php echo stripslashes($centre_name); ?>'
});
var contentString = '<div id="content">'+
'<span id="firstHeading" class="firstHeading"><?php echo stripslashes($centre_name); ?></span>'+
'</div>';
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
var infowindow = new google.maps.InfoWindow({
content: contentString
});
} else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
geocoder.geocode( {'address': addresses[1] }, geocoderCallback);
} else alert("Geocode failed, status:"+status);
}