簡體   English   中英

如何將地址轉換為經度和緯度,然后在頁面上顯示地圖

[英]How to convert an address to longitude and latitude then display a map on the page

我試圖使用谷歌地圖API將我的地址轉換為經度和緯度,然后在頁面上顯示地圖。

只是一個注釋,即時消息使用PHP / Laravel從數據庫中檢索地址。 因此,盡管它是紐約的硬編碼值,但在我開始工作后它將是動態的。

HTML

<div id="map" style="height:250px"></div>

使用Javascript

<script>

    var geocoder = new google.maps.Geocoder();
    var address = "new york";

    geocoder.geocode( { 'address': address}, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.lat();
            var longitude = results[0].geometry.location.lng();
            alert(latitude);
        }
    });

    function initMap() {
        var myLatLng = {lat: latitude, lng: longitude};

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 4,
            center: myLatLng
        });

        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            title: 'Hello World!'
        });
    }




</script>

<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=keyremoved&callback=initMap">
</script>

目前,我收到“未捕獲的ReferenceError:未定義google”錯誤

更改腳本的順序

<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=keyremoved&callback=initMap">
</script>
<script>
   var geocoder = new google.maps.Geocoder();
    var address = "new york";
   // rest of the code
</script>

如上所述,代碼需要放在我的回調函數中。

<script>    
        function initMap(address) {

            var geocoder = new google.maps.Geocoder();

            geocoder.geocode( { 'address': address}, function(results, status) {

                if (status == google.maps.GeocoderStatus.OK) {
                    var latitude = results[0].geometry.location.lat();
                    var longitude = results[0].geometry.location.lng();
                }

                console.log(latitude);
                console.log(longitude);

                var myLatLng = {lat: latitude, lng: longitude};

                var map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 4,
                    center: myLatLng
                });

                var marker = new google.maps.Marker({
                    position: myLatLng,
                    map: map,
                    title: 'Hello World!'
                });

            });


        }




    </script>

    <script async defer
            src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCY2buDtbYIot8Llm_FkQXHW36f0Cme6TI&callback=initMap">
    </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM