谷歌地图移动标记与 lat/lng 从 ajax 成功返回数据

IT技术 javascript ajax google-maps google-maps-api-3
2021-01-13 18:11:12

尝试使用来自 sql db 的经纬度坐标移动标记/地图。

function initialize() {
    var myLatLng = new google.maps.LatLng(41,14);

    var myOptions = {
        zoom: 16,
        center: myLatLng,
        scrollwheel: false,
        panControl: true,
        zoomControl: true,
        mapTypeControl: true,
        scaleControl: true,
        streetViewControl: true,
        overviewMapControl: true,
        mapTypeId: google.maps.MapTypeId.SATELLITE,
    }

    map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

    marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        draggable: false
});

}
google.maps.event.addDomListener(window, 'load', initialize);

function getCoords() {

$.ajax({
url: "../ajaxscript.php",
type: "POST",
data: {
foo : "bar"
},
dataType: "text",
success: function(returnedData) {
      alert(returnedData);
    moveMarkerMap(returnedData);
}
});

}

function moveMarkerMap(newCoords) {
var newLatLang = new google.maps.LatLng(newCoords);
map.panTo(newLatLang);
marker.setPosition(newLatLang);

}
window.setInterval(getCoords, 5000);

在 moveMarkerMap() 中设置新的 google.maps.LatLng(14,41) 将移动它,返回的数据显示在 alert() 中,但与 moveMarkerMap() 一起使用时标记不会移动

ajax 返回的字符串格式正确;(9.624672,7.242244) 如 alert() 所示,所以不确定为什么它不起作用。

1个回答

google.maps.LatLng 构造函数采用两个数字作为参数。这行不通:

var newLatLang = new google.maps.LatLng(newCoords);

您需要将 newCoords 转换为两个数字。

将字符串转换为 latlng 谷歌地图

将“[52.43242, 4.43242]”转换为 google LatLng

如何使用变量中的位置在 Google 地图上获取图钉?

我同意这一点。本来认为这行得通,因为所有经纬度坐标都以该格式存储:) 感谢您指出,我会尝试!
2021-03-14 18:11:12
如果其他人遇到这个问题,拆分字符串:success: function(returnedData) { // alert(returnedData); var coordsArray =returnedData.split(","); moveMarkerMap(coordsArray[0], coordsArray[1]); }
2021-03-20 18:11:12
ajax 调用返回的数据是“13.444,98.7777”......为什么我手动输入它不起作用?
2021-03-24 18:11:12
那是一个字符串,而不是两个数字。
2021-03-31 18:11:12