Steven Kwok Steven Kwok - 3 months ago 11
Javascript Question

(Google map javascript api) - won't display user's current location

I used a 3rd API to locate user's current location then feed the latlng to the initMap function but nothing is showing except a grey screen where the map should be. I also checked the console for errors but there are none. Console.log also return the latlng object with the right values in it. Here is the code:

<script>
var mapDiv = document.getElementById('map');
var pos;
$.get( "http://ip-api.com/json", function(data) {
pos = new google.maps.LatLng(data.lat, data.lon);
});
function initMap() {
var map = new google.maps.Map(mapDiv, {
zoom: 14,
center: pos,
mapTypeControl: false
});
var marker = new google.maps.Marker({
position: pos,
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
title: 'Gotcha!'
});
marker.setMap(map);
}
</script>

Answer

Try this code

  <script type="text/javascript">
      window.onload = function (){
        var mapDiv = document.getElementById('map');
        var pos;
        $.get( "http://ip-api.com/json", function(data) {
          pos = new google.maps.LatLng(data.lat, data.lon);
          initMap();
        });

        function initMap() {
           var map = new google.maps.Map(mapDiv, {
             zoom: 10,
             center: pos

           });
           var marker = new google.maps.Marker({
             position: pos,
             map: map,
             draggable: false,
             animation: google.maps.Animation.DROP,
             title: 'Gotcha!'
           });
        }
      }

  </script>
Comments