Js global number failed?

navigator.geolocation.getCurrentPosition(successCallback);

    function successCallback(position){
        var lat = position.coords.latitude;
        var long = position.coords.longitude;
    }

    var map;
    function initMap() {
      map = new google.maps.Map(document.getElementById("map"), {
        center: {lat: lat, lng: long},
        zoom: 8
      });
    }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=xxx&callback=initMap"
    async defer></script>

Update code ~
so how to transfer lat and long to initMap?


this is normal, because your successCallback is not called, it is a callback function, and your current writing is not necessarily a callback when alert (lat) is executed.

you'd better call initMap from successCallback .


if you want to use it, use it in that successCallback , because only inside can you guarantee this value. Because it is


of asynchronous

reference: https://developer.mozilla.org.
explains that the getCurrentPosition () method is an asynchronous execution method:

* getCurrentPosition() *****

while alert (lat) is Synchronize code, it will be executed first, that is, it will be executed if lat is not assigned, and undefined will be printed

.
Menu