0

正如您在以下代码中看到的那样,我正在从 MySQL 数据库中获取数据,但是当我想使用获取的“位置”来设置谷歌地图上标记的“位置”时,我遇到了困难。

<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxxxxxxx&sensor=true"></script>
<script>
  $.getJSON('http://www.wawhost.com/appProject/fetchmarker.php?callback=?', function(data) {
    for (var i = 0; i < data.length; i++) {
      localStorage.loc = data[i].location;
    }
  });
</script>
<script>
  function initialize() {
    var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
    var mapOptions = {
      zoom: 4,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

    var marker = new google.maps.Marker({
      position: 'new google.maps.LatLng(' + localStorage.loc + ')',
      map: map,
      title: 'Hello World!'
    });
  }
</script>
</head>

<body onload="initialize()">
<div id="map_canvas"></div>
</body>

谢谢!

4

1 回答 1

1

在页面加载后发出请求,并initialize从 AJAX 成功回调中调用该函数。

$(function() {
  $.getJSON('http://www.wawhost.com/appProject/fetchmarker.php?callback=?', function(data) {
     for (var i = 0; i < data.length; i++) {
       localStorage.loc = data[i].location;
     }
     initialize();
  });
});

此外,这条线看起来有点粗略。position应该是新的google.maps.LatLng

position: 'new google.maps.LatLng(' + localStorage.loc + ')'.

LatLng采用纬度和经度参数来构造对象。您从请求中存储的是一个字符串,其中包含逗号分隔的 lat 和 long 值。

// First split the string into lat and long.
var pos = localStorage.loc.split(",");
// Parse the strings into floats.
var lat = parseFloat(pos[0]);
var lng = parseFloat(pos[1]);    
// Create a new marker with the values from the request.  
var marker = new google.maps.Marker({
  position: new google.maps.LatLng(lat, lng),
  map: map,
  title: 'Hello World!'
});

在这里试试

于 2013-01-10T03:32:47.917 回答