1

Below is my code. I have declared the global variables longitude & latitude but if I want to print the alert of longitude or latitude, then the value is only working when I add it inside navigator.geolocation.getCurrentPosition(function(position) { and if I add alert outside like above function initMap() then it showing undefined.

var initMap;
var map;
var longitude;
var latitude;

navigator.geolocation.getCurrentPosition(function(position) {
  console.log("I'm at " + position.coords.latitude + ", " + position.coords.longitude);
  $('body').attr('data-long', position.coords.longitude);
  $('body').attr('data-lat', position.coords.latitude);
  var map;
  var longitude = $('body').attr("data-long");
  var latitude = $('body').attr("data-lat");
  // alert(longitude);
});

alert(latitude);

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: latitude,
      lng: longitude
    },
    zoom: 8
  });
}

var marker_origin = new google.maps.Marker({
  map: map,
  title: "you are here",
  icon: {
    scaledSize: {
      width: 50,
      height: 50
    },
    url: "http://maps.google.com/mapfiles/kml/paddle/blu-blank.png"
  },
  position: {
    lat: latitude,
    lng: longitude
  }
});

{% for row in hubdb_table_rows(table_id) %}    
  var marker_{{ row.hs_id }} = new google.maps.Marker({
    map: map,
    position: {lat: {{ row.location["lat"] }}, lng: {{ row.location["lon"] }}},
    title: '{{ row.name }}',
    icon: { 
      scaledSize: {
        width: 40, 
        height: 40
      }, 
      url: "http://maps.google.com/mapfiles/kml/shapes/dining.png"
    }
  });
 
  marker_{{ row.hs_id }}.addListener('click', function() {
    new google.maps.InfoWindow({
      content: '<div> {{ row.name }} is {{ row.location|geo_distance(request.query_dict['lat'], request.query_dict['lon'], "mi")|round(3) }} miles away</div>'
    }).open(map, marker_{{ row.hs_id }});
  });
{% endfor %}
baxi
  • 155
  • 7
  • The issue is because the `getCurrentPosition` function is asynchronous. This means that you need to place all logic dependent on its response (ie. `longitude` and `latitude` in this case) within the callback, or within functions *called* from that callback. – Rory McCrossan Oct 07 '21 at 11:02
  • Yes I have already defined the ie. longitude and latitude in this case – baxi Oct 07 '21 at 11:14
  • But still it is showing undefined – baxi Oct 07 '21 at 11:14

0 Answers0