Using Google maps API v3 how do I get LatLng with a given address?

前端 未结 3 1420
遥遥无期
遥遥无期 2020-12-07 13:42

If a user inputs an address, I want to convert to the equivalent LatLng.

I\'ve read the documentation, and I think I can use the Geocoder class to do this, but can\'

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 14:09

    There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

    To shorten it up a little:

    geocoder = new google.maps.Geocoder();
    
    function codeAddress() {
    
        //In this case it gets the address from an element on the page, but obviously you  could just pass it to the method instead
        var address = document.getElementById( 'address' ).value;
    
        geocoder.geocode( { 'address' : address }, function( results, status ) {
            if( status == google.maps.GeocoderStatus.OK ) {
    
                //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
                map.setCenter( results[0].geometry.location );
                var marker = new google.maps.Marker( {
                    map     : map,
                    position: results[0].geometry.location
                } );
            } else {
                alert( 'Geocode was not successful for the following reason: ' + status );
            }
        } );
    }
    

提交回复
热议问题