-1

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);

}
yash
  • 2,101
  • 2
  • 23
  • 32
MuthaFury
  • 805
  • 1
  • 7
  • 22

3 Answers3

1

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"].

Jim
  • 3,210
  • 2
  • 17
  • 23
  • Yes but notice that my http is HTTPS not HTTP and I tried your solution, it doesn't work – MuthaFury Jul 21 '16 at 07:37
  • @MuthaFury - I updated the code slightly to ensure `initialize` is always in the global scope so Google's callback will function properly and added a working JSFiddle. – Jim Jul 21 '16 at 07:51
  • No problem, glad I could help! – Jim Jul 21 '16 at 08:02
0

val() function is used to set as well as get the values of an input type element.

While setting the value you are using val(), but while getting their values you have used .value, which I don't think will give you anything or probably an error in your console.

So change that to this:

var lat = document.getElementById("pokemon_lat").val();
var longi = document.getElementById("pokemon_long").val();

See this for a better explanation of how and when to use .val() and when to use .value -> Get the value in an input text box

I hope this will work.

Community
  • 1
  • 1
Ankush Raghuvanshi
  • 1,392
  • 11
  • 17
  • hmmm.... seems like got problem. An error shows up:- `Uncaught TypeError: document.getElementById(...).val is not a function` – MuthaFury Jul 21 '16 at 07:11
  • Oh, i forgot to mention that you'll need to have your jQuery library included in your as .val() is a jQuery function – Ankush Raghuvanshi Jul 21 '16 at 07:13
  • If you're going the jQuery route, you'll have to use `$('#pokemon_lat').val()` like you did to set it in the first place. That `$(selector)` thing wraps the element(s) you're looking for, and gives you all those extra methods like `.val()`. But it sounds like @MuthaFury already tried that... – Whothehellisthat Jul 21 '16 at 07:22
  • Ya, i agree with you @Whothehellisthat. I guess we need the HTML to see if there is something wrong on that side. – Ankush Raghuvanshi Jul 21 '16 at 07:32
  • @MuthaFury, i saw your HTML. Why are all the scripts file being loaded after all the HTML, that too in the body.?? All the JS and CSS is supposed to be placed in the Head, so that they are ready before your HTML is loaded, so that in case any frontend manipulation is required with the HTML elements, JS & CSS are already prepared beforehand, and not that they are being prepared after your HTML has already loaded. Always keep your JS and CSS in head.. Always.!! – Ankush Raghuvanshi Jul 21 '16 at 07:37
  • @AnkushRaghuvanshi: Probably doesn't matter for something still in development, though. And if I understand correctly, nothing happens before all the HTML is loaded. I don't want to derail this question though; I don't think it should affect the problem in any case. – Whothehellisthat Jul 21 '16 at 07:39
-2

Sounds like initialize isn't being run at all. Perhaps the script is loading (or already in-cache) and running before initialize is set up. You could try moving initialize to before the jQuery ready event.

Whothehellisthat
  • 2,072
  • 1
  • 14
  • 14