简体   繁体   中英

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.

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

$(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: 'new google.maps.LatLng(' + localStorage.loc + ')'.

LatLng takes an latitude and longitude argument to construct the object. What you've stored from the request is a string , with comma seperated lat and long values.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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