开发者

Google maps v3 geocoder: callback for latitude and longitude

I can create a Google map that centers on Niwot, CO using geocode. If I click the "Encode" button from the form (which I got from Google's website), it puts a marker on the map in the correct location.

My question is: How do I retrieve the position coordinates (latitude and longitude) using the javascript callback function? I need to put the lat and long into my database.

Also, right now I'm using this for just one place for troubleshooting, but I'll then need it for numerous addresses.

开发者_StackOverflow

Code is below.

var geocoder; var map; function initialize() {

geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.171776, -105.116737);
var myOptions = {
  zoom: 10,
  center: latlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

}

function codeAddress() {

var address = 'Niwot, CO';//this will eventually be an array geocoder.geocode( { 'address': address}, function(results) {

    var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location

    });

//code below added based on comment 1; how do I display that lat and lng? I'll need to do this for troubleshooting.

    var latlng = results[0].geometry.location; 
    var lat = latlng.lat(); 
    var lng = latlng.lng();

}); }


The location returned is an instance of the LatLng class. You can call lat() to get the latitude and lng() to get the longitude. e.g.

var latlng = results[0].geometry.location; var lat = latlng.lat(); var lng = latlng.lng();

Here are the relevant docs:

http://code.google.com/apis/maps/documentation/javascript/reference.html#LatLng


You can do that inside your geocode call

  geocoder.geocode( { 'address': 'CA, US'}, function(results, status) {
   if (status == google.maps.GeocoderStatus.OK) {
     location = results[0].geometry.location;
   alert(location)
    } 
  });

This will show the latitude and longitude of the address.

(lat,lng)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜