佛利斯博客

Javascript 通过地址获取 Google 地图坐标(经纬度)

因为最近又在琢磨 modoer ,一个点评系统,每次都得自己标注地图坐标,很烦人,想整一个自动填写店铺地址,就能获得地址的坐标的功能。网上找到的一段代码,测试了一下,还挺好用的。放上来备份一下。注意需要替换自己的 Google Api key,否则不会成功的。

<!DOCTYPE html>

<html>
<head>
    <title>Test Autocomplete</title>
</head>
<body>

    <script src="https://maps.googleapis.com/maps/api/js?key='change it to api key'&libraries=places"></script>
    <script type="text/javascript">
        google.maps.event.addDomListener(window, 'load', intilize);
        function intilize() {
            var autocomplete = new google.maps.places.Autocomplete(document.getElementById("txtautocomplete"));

            google.maps.event.addListener(autocomplete, 'place_changed', function () {

                var place = autocomplete.getPlace();
                var location = "Address: " + place.formatted_address + "<br/>";
                location += "Latitude: " + place.geometry.location.lat() + "<br/>";
                location += "Longitude: " + place.geometry.location.lng();
                document.getElementById('lblresult').innerHTML = location
            });

        };

    </script>

    <span>location:</span><input type="text" id="txtautocomplete" style="width:200px" placeholder="enter the adress" />
    <br><label id="lblresult"></label>

    <script src="@SiteHelper.GetBaseUrl()/Assets/global/plugins/jquery.min.js" type="text/javascript"></script>
    <script src="@SiteHelper.GetBaseUrl()/Assets/global/plugins/jquery-ui/jquery-ui.min.js" type="text/javascript"></script>
</body>
</html>
退出移动版