0
我們使用MySQL和PHP在常規間隔後存儲當前位置座標(經度和緯度)。這是我們的代碼,用於根據從數據庫中提取的位置座標向地圖添加標記。在Google Maps JavaScript API上自動更新標記位置
我想使用來自數據庫的更新座標自動更新地圖上的標記位置,而無需刷新地圖。我試圖通過互聯網搜索,但無法找到有助於實時更新座標的解決方案。任何幫助將不勝感激。
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng(lat , long),
mapTypeId: 'roadmap'
});
var iconBase = 'XXXXXXX';
var icons = {
spot: {
icon: 'XXXXXX'
},
0: {
icon: iconBase + 'XXXXX'
},
1: {
icon: iconBase + 'XXXX'
},
};
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
map.setCenter(marker.getPosition())
if(feature.type!="spot"){
var content = '<font color="#636363"><h3><img src="http://XXXX"> '+feature.rto+'<br><img style="vertical-align: middle" src="http://XXXXXXX"> <a style="text-decoration:none" href="tel:+91'+feature.phone+'">'+feature.phone+'</a></h3></font>';
}
else {
var content = '<b>Address: </b>'+feature.address+'<br><b>Information: </b>XXXXXXXX';
}
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,this);
};
})(marker,content,infowindow));
}
var features = [
{
<?php echo "position: new google.maps.LatLng(".$lat.", ".$long."),";
echo "type: 'spot',
address: '".$r['address']."'";
?>
}
<?php
$e = mysqli_fetch_assoc(mysqli_query($con, "select distpref,radius from XXXXX XXXXXXXXXXXXXXX"));
$er = $e['radius'];
$dp = $e['distpref'];
$sql = "SELECT *, ($dp * acos(cos(radians(" . $lat . ")) * cos(radians(latitude)) * cos(radians(longitude) - radians(" . $long . ")) + sin(radians(" . $lat . ")) * sin(radians(latitude)))) AS distance FROM markers HAVING distance<$er";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)) {
echo ", {
position: new google.maps.LatLng(".$row['latitude'].", ".$row['longitude']."),
type: '".$row['type']."',
phone: '".$row['phone']."'
}";
}
?>
];
for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=initMap">
</script>`
任何替代解決方案也是可以接受的。
爲實時更新座標,您需要ajax調用php模塊...您應該分割您的代碼..在javascript部分中,用於呈現地圖和基於事件的ajax調用PHP服務器端代碼以檢索新的COORDS並在阿賈克斯成功函數管理與新座標地圖的更新......長..路要走.. – scaisEdge
@scaisEdge我該怎麼辦呢?我可以調用ajax,但是如何更新標記的位置? –
在ajax調用中你有一個成功的函數...然後用這個函數可以調用一個簡單的標記設置位置,例如:var latlng = new google.maps.LatLng(your_new_lat,your_new_lng); marker.setPosition(經緯度); – scaisEdge