Я хочу отображать несколько карт Google с моей широтой и долготой из MySQL, и я использую цикл. Вот мой код:
<style>
.my_map {
height: 400px;
width: 100%;
}
</style>
<div>
<?php
foreach($clinics AS $clinic) {
?>
<div class = "my_map" id = "map_<?php print($clinic->id); ?>" >
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map_<?php print($clinic->id); ?>'), {
center: {lat: <?php print($clinic->latitude); ?>, lng: <?php print($clinic->longitude); ?>},
zoom: 16
});
}
</script>
</div>
<?php
}
?>
</div>
<script async defer
src = "https://maps.googleapis.com/maps/api/js?key=MY_KEY_HERE&callback=initMap">
</script>
Моя проблема в том, что отображается только последняя карта, в то время как предыдущие не отображают карты. Не следует ли писать сценарий внутри цикла? Спасибо.






вы должны использовать foreach .. : end foreach, например:
<div>
<?php foreach($clinics AS $clinic) : ?>
<div class = "my_map" id = "map_<?php print($clinic->id); ?>" >
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map_<?php print($clinic->id); ?>'), {
center: {lat: <?php print($clinic->latitude); ?>, lng: <?php print($clinic->longitude); ?>},
zoom: 16
});
}
</script>
</div>
<?php endforeach; ?>
</div>
Пока не тестировался, я бы предложил подход, похожий на этот. Создайте переменную javascript со всеми исходными данными из переменной php $clinics - в данном случае json - и используйте функцию initMap для итерации по этой переменной / данным, создавая объект карты на каждой итерации.
<style>
.my_map {
height: 400px;
width: 100%;
}
</style>
<script async defer src = "//maps.googleapis.com/maps/api/js?key=MY_KEY_HERE&callback=initMap"></script>
<script>
var obj,map;
<?php
/*
assuming that `$clinics` is an array and that each member is also an array
with constituent keys id,latitude,longitude which is how it appears to be
from the original question
encode as json data
*/
$json=json_encode( $clinics );
/* create javascript variable with data */
echo "
var json = {$json};
";
?>
function initMap(){
/* iterate through json data */
for( var n in json ){
obj=json[n];
map=new google.maps.Map( document.querySelector('div[ data-id = "'+n+'" ]'),{
center:{ lat:parseFloat( obj.latitude ), lng:parseFloat( obj.longitude ) },
zoom:16
});
}
}
</script>
<?php
/*
generate containers to hold each map based upon original array
*/
foreach( $clinics as $index => $clinic ){
echo "<div class='my_map' data-id='{$index}'></div>";
}
?>
Мы попробовали код, предложенный RamRaider, однако нам не удалось отобразить карты. Чтобы он заработал, нам пришлось прикрепить вызов сценария инициализации к концу страницы. Таким образом, код становится:
<style>
.my_map {
height: 400px;
width: 100%;
}
</style>
<script>
jQuery(function() {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "//maps.googleapis.com/maps/api/js?key=MY_KEY_HERE&callback=initMap";
document.body.appendChild(script);
});
var obj,map;
<?php
/*
assuming that `$clinics` is an array and that each member is also an array
with constituent keys id,latitude,longitude which is how it appears to be
from the original question
encode as json data
*/
$json=json_encode( $clinics );
/* create javascript variable with data */
echo "
var json = {$json};
";
?>
function initMap(){
/* iterate through json data */
for( var n in json ){
obj=json[n];
map=new google.maps.Map( document.querySelector('div[ data-id = "'+n+'" ]'),{
center:{ lat:parseFloat( obj.latitude ), lng:parseFloat( obj.longitude ) },
zoom:16
});
}
}
</script>
<?php
/*
generate containers to hold each map based upon original array
*/
foreach( $clinics as $index => $clinic ){
echo "<div class='my_map' data-id='{$index}'></div>";
}
?>
Сценарий никогда не следует писать в цикле. Скорее маркер должен быть в цикле. Проверьте эту ссылку stackoverflow.com/questions/18480105/… и при необходимости измените коды. Оно работает