victoria
victoria

Reputation: 207

JSON get geolocation not returning value in HTML

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.

Upvotes: 0

Views: 125

Answers (1)

Tom Mettam
Tom Mettam

Reputation: 2963

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

Upvotes: 1

Related Questions