Search code examples
javascripthtmlgeolocationmaps

HERE Maps using HTML5 Geolocation


I have a problem using the HTML5 Geolocation API with HERE Maps. First I made a test document which works properly:

var test = document.getElementById('test');

var coords = navigator.geolocation.getCurrentPosition(success);

function success(position) {
      test.innerHTML = 'Latitude: ' + position.coords.latitude +
                       "<br>Longitude: " + position.coords.longitude;
}

http://jsfiddle.net/d8age6ss/

After that I tried to add that code into my HERE Map:

var coords = navigator.geolocation.getCurrentPosition(success);

function success(position) {
    var location = '{ lat: ' + position.coords.latitude + ', lng: ' + position.coords.longitude; + ' }'
}        

function setView(map) {
    map.setCenter(location);
    map.setZoom(12);
}

What I do not see is what is wrong. On https://developer.here.com/javascript-apis/documentation/maps it is said that HTML5 Geolocation is supported.

Thanks for your help!


Solution

  • Your problem is you have a local variable in your success function:

    function success(position) {
        var location = ...
    }        
    

    Only that function can use that variable. So when you try to use it again in the setView function, it won't know what it is.

    function setView(map) {
        map.setCenter(location);
    

    Instead what you need to do is either make location a global variable, or pass it as a parameter into your setView function. e.g.

    var location;
    
    function success(position) {
        location = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
    }        
    
    function setView(map) {
        map.setCenter(location);
        map.setZoom(12);
    }
    

    (Also location doesn't need to be created as a string, so I amended that slightly).

    I don't see where you call setView from?