0

I am trying to get geo coordinates and then return them into my HTML. This is the code I have so far, but it is not returning the coordinates onto my page:

   if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    $("#cityname").html("latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude);
  });
}  

I have an id in my html named 'cityname'. I would also like to convert the coordinates into a city name.

victoria
  • 197
  • 1
  • 1
  • 12
  • if you console.log(position) does anything get logged to the console? – Kyle Apr 18 '16 at 15:35
  • was there popup from browser which asked for allowing to share position with page? you should add fallback code for case when user disagree with this, and blocks position sharing – llamerr Apr 18 '16 at 15:36
  • if you accidently blocked that popup, you can reset it https://support.google.com/chrome/answer/142065?hl=en-GB – llamerr Apr 18 '16 at 15:39

1 Answers1

1

Your code seems to work just fine:

https://jsfiddle.net/sexepm39/

Perhaps your div isn't available in the DOM when this code runs?

Try wrapping it as such:

$(document).ready(function() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            $("#cityname").html("latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude);
        });
    }
});

As for getting the city name, this part of your question is already answered: Get city name using geolocation

Community
  • 1
  • 1
Tom Mettam
  • 2,903
  • 1
  • 27
  • 38