-1

I'm working with Google Maps JS API. I'm trying to set a marker at the center of my map. I'm using the currLocation variable to hold the current location. The currLocation variable has value within the inline private method ( Section 1), but it is null when I want to set a marker(Section 2).

Stackoverflow had lot of solutions for "Unable to set value to global variable", but I couldn't solve my issue with their reference.

Any help would be appreciated.

function initMap() {

    var currLocation = null;

    var defaultCenter = { lat: 34.397, lng: 150.644 };

    //Set Map properties 
    var map = new google.maps.Map(document.getElementById('gmap'), {
        scrollwheel: true,
        zoom: 10
    });


    //Get Current Location - Section 1 
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            currLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            map.setCenter(currLocation);
        });
    }
    else {
        map.setCenter(defaultCenter);
    }

    //Put marker on the current location - Section 2
    var marker = new google.maps.Marker({
        position: currLocation,
        map: map
    });
}
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Ranjith V
  • 298
  • 1
  • 3
  • 16

2 Answers2

0

Well the problem lies within your control flow logic. If the first feature detection fails (I.e., if(navigator.geolocation)) (from your description, it sounds exactly like that), then the value of currLocation will remain null. If, it is not desirable to continue without currLocation then:

  1. Throw an exception from your else block as, navigator does not have geolocation.
  2. Set it to an acceptable default other than null.
Abrar Hossain
  • 2,594
  • 8
  • 29
  • 54
0

You're supposed to put the marking function inside the success callback of getCurrentPosition. Because it's an asynchronous function. currLocation would be null until the success callback function is called.

jee1mr
  • 31
  • 3