简体   繁体   English

在JavaScript中设置变量的值

[英]Setting the value of a variable in JavaScript

As you can see in the following code I'm fetching data from the MySQL database, but I got stuck when I wanted to use fetched "location" to set the "position" of a marker on a google map. 如您在以下代码中看到的那样,我正在从MySQL数据库中获取数据,但是当我想使用获取的“位置”来设置Google地图上标记的“位置”时,我陷入了困境。

<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>

Thank you! 谢谢!

Make the request when the page has loaded, and call the initialize function from the AJAX success callback. 页面加载后发出请求,并从AJAX成功回调中调用initialize函数。

$(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();
  });
});

Also, this line looks a bit sketchy. 另外,这条线看起来有些粗略。 position is supposed to be a new google.maps.LatLng . position应该是新的google.maps.LatLng

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

LatLng takes an latitude and longitude argument to construct the object. LatLng采用纬度和经度参数来构造对象。 What you've stored from the request is a string , with comma seperated lat and long values. 您从请求中存储的是一个字符串 ,带有逗号分隔的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!'
});

Try it here. 在这里尝试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM