繁体   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