MuthaFury MuthaFury - 4 months ago 34
jQuery Question

failed to get input value by id

I have this code, that detect the longitude and latitude, it managed to put into input but I'm not able to retrieve the input value, please help me find what is the issue. I tried jquery, it can't retrieve either.

Here is my code:-

var startPos;
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
$('#pokemon_lat').val(startPos.coords.latitude);
$('#pokemon_long').val(startPos.coords.longitude);

}, function(error) {
alert('Error occurred. Error code: ' + error.code + '');
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable (error response from locaton provider)
// 3: timed out
});

$(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "//maps.googleapis.com/maps/api/js?key=shcschds&sensor=true&callback=initialize";
document.body.appendChild(script);
});

function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};

// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);

// Multiple Markers LatLong
var lat = document.getElementById("pokemon_lat").value;
var longi = document.getElementById("pokemon_long").value;

console.log('Lat:'+lat+' Long:'+longi);

}

Jim Jim
Answer

INITIAL WARNING: As of Chrome 50, the Geolocation API is disabled unless you are on an encrypted connection (https://) which means this will not work at all on an insecure localhost or any other insecure (http://) server. Firefox is also pondering implementing this as well.

Your initialize function is likely being called before the Geolocation API returns a value and/or is accepted. Try using a promise/jQuery deferred (since your code indicates you are using jQuery) to indicate when the API has completed or failed:

    var startPos, positionPromise = $.Deferred();

navigator.geolocation.getCurrentPosition(function(position) {
    startPos = position;
    $('#pokemon_lat').val(startPos.coords.latitude); 
    $('#pokemon_long').val(startPos.coords.longitude);

    // Huston, we have the location!
    positionPromise.resolve();

}, function(error) {
    alert('Error occurred. Error code: ' + error.code + '');
    // error.code can be:
    //   0: unknown error
    //   1: permission denied
    //   2: position unavailable (error response from locaton provider)
    //   3: timed out

    // Danger, Will Robinson! Danger!
    positionPromise.reject();

});

window["initialize"] = function() {
    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap'
    };

    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setTilt(45);

    // Multiple Markers LatLong
    $.when(positionPromise).then(function(){
            var lat = document.getElementById("pokemon_lat").value;
            var longi = document.getElementById("pokemon_long").value;
            console.log('Lat:'+lat+' Long:'+longi);
        }, function(){
            console.log("Could not get latitude and longitude )-:");
        }
    );

}

$(function($) {
    // Asynchronously Load the map API 
    var script = document.createElement('script');
    script.src = "//maps.googleapis.com/maps/api/js?key=shcschds&sensor=true&callback=initialize";
    document.body.appendChild(script);
});

UPDATE: Updated code and working JSFiddle. For some reason the initialize function was not being set in the global scope (possibly being added through an outer function). To ensure initialize is in the global scope you use window["initialize"].