Google maps API v3 - Marker disappears after setPo

2019-07-27 06:32发布

This question already has an answer here:

I'm having a problem with the maps markers. The map and marker load fine on the inital pageload. But when I try to update the marker location it simply disappears. The Alert window gives the correct coördinates. What am I doing wrong here?

Code:

<script>
var myCenter=new google.maps.LatLng(<?php echo $loc; ?>);

function initialize()
{
  var mapProp = {
  center:new google.maps.LatLng(<?php echo $loc; ?>),
  zoom:15,    
  mapTypeId:google.maps.MapTypeId.ROADMAP,
  };
var map=new google.maps.Map(document.getElementById("googleMap")
,mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});

marker.setMap(map);                 

setInterval(function(){ 
    jQuery.get('loc.php?v=<?php echo $_GET['voertuignummer'];?>', function(data) {
alert(data);
position = new google.maps.LatLng(data);
marker.setPosition(position);
map.setCenter(position);
    });

}, 15000);

}

google.maps.event.addDomListener(window, 'load', initialize);
</script>

1条回答
Melony?
2楼-- · 2019-07-27 07:28
function(data) {
   alert(data);
   position = new google.maps.LatLng(data);
   ..

Looks very wrong; data is a string, probably containing "lat, lng", which google.maps.LatLng cannot be initialized with. new google.maps.LatLng requires a pair of type number in the arguments, like (number, number).

Do this instead :

data = data.split(',');
position = new google.maps.LatLng(parseFloat(data[0]), parseFloat(data[1]));
查看更多
登录 后发表回答