Whogohost Advert On NCT|
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Getting Current Location With Javascript
#1
I originally thought grabbing a user's current location was going to be difficult, but it's actually very simple.
There's quick way on w3schools that shows us how to use HTML5

Geolocation API:

http://www.w3schools.com/html/html5_geolocation.asp

You also have to include the Google Maps API:

http://maps.googleapis.com/maps/api/js?sensor=false

Then you write your function to grab the current location:


Code:
function getLocation() {
    if(navigator.geolocation {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
        } else {
            alert("Geolocation is not supported by this browser.");
        }
    }

You'll also need to write your success function:


Code:
function geoSuccess(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    alert("lat:" + lat + " lng:" + lng);
}


And then an error function:


Code:
function geoError() {
    alert("Geocoder failed.");
}


You can stop here if you just want the lat and lng coordinates.
But if you want to convert these coordinates to a full address, you can call another function that passes your lat and lng:
Add a function in your success function:


Code:
function geoSuccess(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    alert("lat:" + lat + " lng:" + lng);
    codeLatLng(lat, lng);
}

And here's the code for that function:


Code:
var geocoder;
function initialize() {
    geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if(status == google.maps.GeocoderStatus.OK) {
          console.log(results)
          if(results[1]) {
              //formatted address
              var address = results[0].formatted_address;
              alert("address = " + address);
          } else {
              alert("No results found");
          }
      } else {
          alert("Geocoder failed due to: " + status);
      }
    });
}


Answer found from:

http://stackoverflow.com/questions/67975...-city-name
It takes so long to learn simplicity.
[-] The following 1 user Likes Dealwap's post:
  • Nkakad
Facebook Share


Possibly Related Threads...
Thread
  HELP: How Can I Create A Javascript Ads Rotator For My Site
  Beginner Javascript Coding Mistakes To Avoid
  Concatenate Many Arrays Uniquely With Javascript
  Javascript Time Ago Function
  Shortest Code For Random Number Between 1 And N In Javascript
  Javascript Text Editor Right In Your Browser In One Line Of Code
  How To Check If Javascript Object Is Empty
  How To Create An Image Slider With Javascript
  Convert Numbers To Roman Numerals With Javascript
  TUTORIAL: How To Make A Digtal Clock With Javascript




Users browsing this thread: 2 Guest(s)