How to find the lat lng from a geocoded address?

前端 未结 2 1543
时光取名叫无心
时光取名叫无心 2021-01-24 15:21

I\'m trying to create a Gmap to allow people to geocode an address and find the respective lat lng. I would like to see this in the forms I\'ve already created. Also, I would li

相关标签:
2条回答
  • 2021-01-24 16:02

    Inside the geocoder call back do this:

    document.getElementById('lat').value = results[0].geometry.location.lat();
    document.getElementById('lng').value = results[0].geometry.location.lng();
    

    Working example

    0 讨论(0)
  • 2021-01-24 16:06

    Ok... here's the code that makes what I wanted to. It might not be that elegant, but it works. I used the getPosition() method to get the coordinates, just have to click in the geocoded marker!

    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="UTF-8">
        <title>Geocoder</title>
    <style>
    #map_canvas { width:400px; height:450px; }
    </style>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
    </script>
    <script type="text/javascript">
    
    var geocoder;
    var map;
    
    function initialize() {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(-30.070, -51.190);
        var myOptions = {
            zoom: 9,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }
    
    function codeAddress() {
        var address = document.getElementById("address").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    draggable: true,
                });
    
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
            google.maps.event.addListener(marker, 'click', function() {
                document.getElementById('coords').value = marker.getPosition();
            });
        });
    }
    
    </script>
    </head>
    
    <body onload="initialize()">
    <div id="map_canvas"></div>
    <div id="info"></div>
    <div>
        <input id="address" type="textbox" value="">
        <input type="button" value="Localizar!" onclick="codeAddress()"><br>
        <input type="textbox" id="coords">
        </div>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题