简体   繁体   中英

Google Maps GeoCoder Issue

I'm trying to make a simple page that allows addresses from a mysql database to be converted to lat and long and then displayed as markers on a map.

Most of the code below comes from the google docs with the addition of some geocoder stuff.

I can successfully alert the correct coordinates (see line 48-53) but then I try to pass them into 'point' variable for google maps to create a marker but nothing appears on the map.

Can anyone see whats wrong with my code? I'm not familiar with Javascript so it could be something really fundamentally wrong.

Thanks

 function load() {
 geocoder = new google.maps.Geocoder();
 map = new google.maps.Map(document.getElementById("map"), {
   center: new google.maps.LatLng(47.6145, -122.3418),
   zoom: 3,
   mapTypeId: 'roadmap'
 });
 var infoWindow = new google.maps.InfoWindow;

 // Change this depending on the name of your PHP file
 downloadUrl("phpsqlajax_genxml3.php", function(data) {
   var coords;
   var xml = data.responseXML;
   var markers = xml.documentElement.getElementsByTagName("marker");
   for (var i = 0; i < markers.length; i++) {
     var name = markers[i].getAttribute("name");
     var address = markers[i].getAttribute("address");
     var type = markers[i].getAttribute("type");

     geocoder.geocode( { 'address': address}, function(results, status) {
       var latpoint = parseFloat(results[0].geometry.location.lat());
       var lngpoint = parseFloat(results[0].geometry.location.lng());
       coords = latpoint + ', ' + lngpoint;
       //alert(coords); //For Testing
     });

     var point = new google.maps.LatLng(coords);
     var html = "<b>" + name + "</b> <br/>" + address;
     var icon = customIcons[type] || {};
     var marker = new google.maps.Marker({
       map: map,
       position: point,
       icon: icon.icon,
       shadow: icon.shadow
     });
     bindInfoWindow(marker, map, infoWindow, html);
   }
 });

}

The LatLng object constructor is waiting for Number type. Here you give it a string with the concatened coordinates, wich is wrong. Look at the doc here .

Try that instead :

var latpoint = parseFloat(results[0].geometry.location.lat());
var lngpoint = parseFloat(results[0].geometry.location.lng());

var point = new google.maps.LatLng(latpoint, lngpoint);

And please refer to the @Pekka 웃 comment to be sure people answer you next time.

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