我试图显示我在我的数据库中的每个地址的标记。我将地址存储在javascript数组中,并对它们进行地理编码,以便在地图上显示每个地址的标记。地址被存储在数组中,但不幸的是,只有最后一个地址在map上得到标记。
<script>
var addresses = [];
<?php
if(is_array($fetchData)){
$sn=1;
foreach($fetchData as $data){
$post = $data['post'];
$city = $data['city'];
$street = $data['street'];
$number = $data['number'];
?>
var address = '<?php echo $data['post'] . ' ' . $data['city'] . ' ' . $data['street'] . ' ' . $data['number']; ?>';
addresses.push(address);
var geocoder;
var map;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
});
var i = 0;
geocoder[i] = new google.maps.Geocoder();
codeAddress(geocoder, map);
}
function codeAddress(geocoder, map) {
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
i++;
<?php
$sn++;}}else{ ?>
<?php
}?>
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MyKey&callback=initMap">
</script>
我正在考虑索引'geocoder'并在循环结束时做'i++;',但它还不起作用。
通常您会运行db查询并将PHP结果转换为可以在Javascript中处理的变量。JSON非常适合用于此目的——易于在PHP中生成,并且易于在Javascript中处理。
你可以考虑这样处理,未经测试的例子:
<script>
<?php
// convert db results array into JSON and echo as a js variable.
printf('const addresses=%s;', json_encode( is_array( $fetchData ) ? $fetchData : [] ) );
?>
/*
create the map and declare once the geocoder etc
*/
function initMap() {
let map = new google.maps.Map(document.getElementById('map'), {
zoom: 8
});
let geocoder = new google.maps.Geocoder();
let codeAddress=( address )=>{
geocoder.geocode({'address': address }, function(results, status) {
if (status === 'OK') {
map.setCenter( results[0].geometry.location );
let marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
};
/*
iterate through the JSON data to call the geocoder function for each result
*/
Object.keys( addresses ).forEach(key=>{
let obj=addresses[ key ];
let address=`${obj.post} ${obj.city} ${obj.street} ${obj.number}`;
codeAddress.call( this, address );
});
}
</script>
<script async defer src="//maps.googleapis.com/maps/api/js?key=MyKey&callback=initMap"></script>