Javascript - Save Geolocation Coordinates - javascript

How can i save the coordinates in localstorage so that it shouldn't ask the users every time to allow GPS or Location and a button to clear the localstorage value so it can again ask for coordinates?
FYI:
I am using Praytimes JS to display Muslim prayer times but for each location i have to manually add latitude & longitude of that location.
Below is my code:
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var x = document.getElementById("currentlocation");
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
$('#currentlocation').html("Geocoder failed");
}
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
$('#currentlocation').html(results[0].formatted_address);
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
$('#currentlocation').html(city.short_name + " " + city.long_name)
} else {
$('#currentlocation').html("No results found");
}
} else {
$('#currentlocation').html("Geocoder failed due to: " + status);
}
});
}
</script>
<p id="currentlocation"></p>
<script type="text/javascript" src="http://praytimes.org/code/v2/js/PrayTimes.js"></script>
<script type="text/javascript">
function loadTable(position) {
prayTimes.setMethod('MWL');
var date = new Date(); // today
var times = prayTimes.getTimes(date, [position.coords.latitude, position.coords.longitude]);
var list = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha', 'Midnight'];
var html = '<table id="timetable">';
html += '<tr><th colspan="2">'+ date.toLocaleDateString()+ '</th></tr>';
for(var i in list) {
html += '<tr><td>'+ list[i]+ '</td>';
html += '<td>'+ times[list[i].toLowerCase()]+ '</td></tr>';
}
html += '</table>';
document.getElementById('table').innerHTML = html;
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(loadTable);
}
</script>

Define an object with the informations of the coordinates:
var coordinatesObject =
{
lat: position.coords.latitude,
lng: position.coords.longitude
}
Save it in the local storage:
localStorage.setItem('coordinates',
JSON.stringify(coordinatesObject));
Get it:
let objFromLocalStorage =
localStorage.getItem('coordinates');

var CACHED_POSITION = "CACHED_POSITION";
var x = document.getElementById("currentlocation");
var geocoder;
(function () {
if (navigator.geolocation) {
try {
var position = JSON.parse(window.localStorage[CACHED_POSITION]);
if (position) {
successFunction(position);
return;
}
} catch (e) {
}
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
})();
//Get the latitude and the longitude;
function successFunction(position) {
window.localStorage[CACHED_POSITION] = JSON.stringify(position);
var lat = position.coords.latitude;
var lng = position.coords.longitude;//Save to cache
codeLatLng(lat, lng);
}

Related

Getting error Geocoder failed while fetching current location using JavaScript

I am getting the following error while trying to fetch current location using Google Maps API.
Error:
Geocoder failed
I am providing my code below.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
function getDefaultLocation(){
setTimeout(function(){
var geocoder='';
geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
console.log("Geocoder failed");
}
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){
if (results[1]) {
var indice=0;
for (var j=0; j<results.length; j++){
if (results[j].types[0]=='locality'){
indice=j;
break;
}
for (var i=0; i<results[j].address_components.length; i++){
if (results[j].address_components[i].types[0] == "locality") {
city = results[j].address_components[i];
}
if(results[j].address_components[i].types[0] == "administrative_area_level_1"){
region = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "country"){
country = results[j].address_components[i];
}
if(results[j].address_components[i].types[0] == "route"){
locality=results[j].address_components[i];
}
}
}
// console.log('final result',city.long_name,region.long_name,country.long_name,locality.long_name);
var city=city.long_name;
var country=country.long_name;
var locality=locality.long_name;
document.getElementById('bindCon').innerHTML=country; document.getElementById('bindCit').innerHTML=city; document.getElementById('bindloc').innerHTML=locality;
}else{
console.log("No results found");
}
}else{
console.log("Geocoder failed due to: " + status);
}
})
}
},5000);
}
The above code is working properly in localhost but while putting this into my testing site (http://xxxx.com) the above error is coming. Here I need to fetch all the required data.

How to pass javascript alert message value to label in asp.net

I had implemented geolocation , wherein browser gets location of user.
In this code i'm getting geolocation of user through browser ,but it display location using javascript alert message.
I just want to pass alert message value to label or hiddenfield in ASP.Net & doesn't want to run alert message
My javascript code as follows.
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction() {
alert("Geocoder failed");
}
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
alert(results[0].formatted_address)
//find country name
for (var i = 0; i < results[0].address_components.length; i++) {
for (var b = 0; b < results[0].address_components[i].types.length; b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
document.getElementById('<%=Label1.ClientID %>').innerHTML = city;
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
If you want to store the value in a hidden field replace
alert(results[0].formatted_address)
with
//hdnField is the ID of your asp:HiddenField object
var hiddenField = document.getElementById("<%= hdnField.ClientID %>")
hiddenField.value = results[0].formatted_address;

javascript argument not passing through a function

i'm trying to get a user's current city plus whatever argument that's being passed through getCity function when clicked but i'm getting undefined for 'x' variable. here's the code..
<button onclick="getCity('burger')">burger</button>
<button onclick="getCity('steak')">steak</button>
<button onclick="getCity('taco')">taco</button>
<script type="text/javascript">
//get city
function getCity(x) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPos);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
//get lat and long
function showPos(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//get address
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//get city
if (results[0]) {
var city = results[0]['address_components'][2].long_name;
var x = x;
alert(x +" "+ city); // i'm getting undefined + currentcity
}
}
});
}
</script>
i'm getting undefined + currentcity. how do i make it so i get burger + currentcity if i click on burger button?
You second last statement
var x = x;
asssigns an undefined x to x. Both "x"s are undefined.
For your script to work you have to declare a global variable
<button onclick="getCity('burger')">burger</button>
<button onclick="getCity('steak')">steak</button>
<button onclick="getCity('taco')">taco</button>
<script type="text/javascript">
var food;
//get city
function getCity(x) {
if (navigator.geolocation) {
food = x;
navigator.geolocation.getCurrentPosition(showPos);
} else {
//x.innerHTML does not work because x is a string not an element
this.innerHTML = "Geolocation is not supported by this browser.";
}
}
//get lat and long
function showPos(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//get address
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//get city
if (results[0]) {
var city = results[0]['address_components'][2].long_name;
var x = food;
alert(x +" "+ city);
}
}
});
}
</script>
Another possible solution would be passing it to pass the x to the showPos function.
<button onclick="getCity('burger')">burger</button>
<button onclick="getCity('steak')">steak</button>
<button onclick="getCity('taco')">taco</button>
<script type="text/javascript">
//get city
function getCity(x) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
showPos(position, x);
});
} else {
//x.innerHTML does not work because x is a string not an element
this.innerHTML = "Geolocation is not supported by this browser.";
}
}
//get lat and long
function showPos(position, x) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//get address
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//get city
if (results[0]) {
var city = results[0]['address_components'][2].long_name;
//var x = food; x is already a parameter of this function so don't declare it again
alert(x +" "+ city);
}
}
});
}
</script>

Placing Geolocated Coordinates in a jQuery File

I am having difficulty inserting the geolocated coordinates (latitude and longitude) of the current user's location into a PHP/MySQL generated xml file. It requires the user's geolocation to correctly generate the 20 closest businesses within a 30-mile radius. I am currently using a jQuery-powered store locator script to generate the map. The script works fine with a static URL as the xmlLocation, but when I try to use variables in the URL it just outputs an undefined alert message. My aim is to get javascript to place the latitude and longitude values of the user's location into the PHP GET variables so that the XML generator can generate correct output. It looks like this:
LocationGlobal = 'data/gen_default_map.php?lat=' + lat + '&lng=' + lon + '&radius=30';
And should ouput something like this:
data/gen_default_map.php?lat=34.383747&lng=-82.364574&radius=30
I have made modifications to the script and placed comments accordingly. You probably only need to concern yourself with the first 42 lines of the code, but just in case here is the script in it's entirety:
/* Get the User's Current Location and place it in the URL */
/*--------------------------------------------------*/
var LocationGlobal;
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
var lat = position.coords.latitude;
var lon = position.coords.longitude;
LocationGlobal = 'data/gen_default_map.php?lat=' + lat + '&lng=' + lon + '&radius=30';
alert(LocationGlobal); // Sets correctly here
return LocationGlobal;
});
} else {
console.log('Error getting coordinates.');
}
alert(LocationGlobal); // Undefined here
/*--------------------------------------------------*/
(function ($) {
$.fn.storeLocator = function (options) {
var settings = $.extend({
'mapDiv': 'map',
'listDiv': 'list',
'formID': 'user-location',
'pinColor': 'fe7569',
'startPinColor': '66bd4a',
'pinTextColor': '000000',
'storeLimit': 10,
'distanceAlert': 60,
'xmlLocation': LocationGlobal, //'data/gen_default_map.php?lat=34&lng=-82&radius=30', <--- the commented static URL works but variable doesn't
'addressErrorMsg': 'Please enter valid address address or postcode',
'googleDistanceMatrixDestinationLimit': 25,
'defaultLat': 34.8483680,
'defaultLng': -82.400440,
'defaultLocationName': 'Greenville, South Carolina'
}, options);
return this.each(function () {
var $this = $(this);
// global array of shop objects
var _locationset = new Array();
var geocoder;
// Calculate distances from passed in origin to all locations in the [_locationset] array
// using Google Maps Distance Matrix Service https://developers.google.com/maps/documentation/javascript/reference#DistanceMatrixService
var GeoCodeCalc = {};
GeoCodeCalc.CalcDistanceGoogle = function (origin, callback) {
var destCoordArr = new Array();
var subFunctionTokens = [];
$.each(_locationset, function (ix, loc) {
destCoordArr.push(loc.LatLng);
});
for (var i = 0; i < destCoordArr.length; i = i + settings.googleDistanceMatrixDestinationLimit) { // Google Distance Matrix allows up to 25 destinations to be passed in
var tempArr = destCoordArr.slice(i, Math.min(i + settings.googleDistanceMatrixDestinationLimit));
subFunctionTokens.push(this.CallGoogleDistanceMatrix(i, origin, tempArr));
}
$.when.apply($, subFunctionTokens)
.then(function () {
callback(true);
});
};
GeoCodeCalc.CallGoogleDistanceMatrix = function (startIndex, origin, destinations) {
var token = $.Deferred();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: destinations,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
}, function (response, status) {
if (response && response.rows.length) {
var results = response.rows[0].elements;
$.each(results, function (j, val) {
if (results[j].status != "ZERO_RESULTS") {
_locationset[startIndex + j].Distance = GoogleMapDistanceTextToNumber(results[j].distance.text);
}
});
token.resolve();
}
});
return token.promise();
};
// Converts "123.45 mi" into 123.45
function GoogleMapDistanceTextToNumber(str) {
return Number(str.replace(/[^0-9.]/g, ""));
}
// removes Google Maps URL unfriendly chars from a string
function formatGoogleMapUrlString(str) {
return str.replace("&", "%26").replace(" ", "+");
}
//Geocode function for the origin location
geocoder = new google.maps.Geocoder();
function GoogleGeocode() {
this.geocode = function (address, callbackFunction) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var result = {};
result.latitude = results[0].geometry.location.lat();
result.longitude = results[0].geometry.location.lng();
result.formatted_address = results[0].formatted_address;
result.address_components = results[0].address_components;
callbackFunction(result);
} else {
handleError("Geocode was not successful for the following reason: " + status);
callbackFunction(null);
}
});
};
this.geocodeLatLng = function (LatLng, callbackFunction) {
geocoder.geocode({ 'location': LatLng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
callbackFunction(results[0]);
} else {
handleError("Geocode was not successful for the following reason: " + status);
callbackFunction(null);
}
});
};
}
//Process form input
$(function () {
$(document).on('submit', '#' + settings.formID, function (e) {
$("#lblError").html("");
//Stop the form submission
e.preventDefault();
//Get the user input and use it
var userinput = $('form').serialize();
userinput = userinput.replace("address=", "");
if (userinput == "") {
handleError(settings.addressErrorMsg);
}
var g = new GoogleGeocode();
var address = userinput;
g.geocode(address, function (data) {
if (data != null) {
showAddress(data);
mapping(data.latitude, data.longitude);
} else {
//Unable to geocode
handleError(settings.addressErrorMsg);
}
});
//Replace spaces in user input
userinput = formatGoogleMapUrlString(userinput);
});
});
$(document).ready(function () {
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
//map.setCenter(pos);
var g = new GoogleGeocode();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
g.geocodeLatLng(latlng, function (address) {
if (address) {
showAddress(address);
} else {
//Unable to geocode
handleNoGeolocation('Error: Unable to geocode address');
}
});
// do the mapping stuff
mapping(position.coords.latitude, position.coords.longitude);
}, function () {
handleNoGeolocation("Tracking of location was not allowed.");
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
});
function showAddress(address) {
$("#lblAddress").html(address.formatted_address);
// find a postcode and show it in the address textbox
$.each(address.address_components, function (i, val) {
if (val.types[0] == "postal_code") {
$("#address").val(val.short_name);
return false; // breaks the each() loop
}
});
}
function handleNoGeolocation(error) {
if (error) {
var content = error;
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
handleError(content + " Using default location.");
mapping(settings.defaultLat, settings.defaultLng);
$("#lblAddress").html(settings.defaultLocationName);
}
function handleError(error) {
$("#lblError").html(error);
}
//Now all the mapping stuff
function mapping(orig_lat, orig_lng) {
$(function () {
//Parse xml with jQuery
$.ajax({
type: "GET",
url: settings.xmlLocation,
dataType: "xml",
success: function (xml) {
_locationset = new Array();
$(xml).find('Placemark').each(function (i) {
var shop = {
Name: $(this).find('name').text(),
//Take the lat lng from the user, geocoded above
LatLng: new google.maps.LatLng(
$(this).find('coordinates').text().split(",")[1],
$(this).find('coordinates').text().split(",")[0]),
Description: $(this).find('description').text(),
Marker: null,
Distance: null
};
_locationset.push(shop);
});
// Calc Distances from user's location
GeoCodeCalc.CalcDistanceGoogle(new google.maps.LatLng(orig_lat, orig_lng), function (success) {
if (!success) { //something went wrong
handleError("Unable to calculate distances at this time");
}
else {
//Sort the multi-dimensional array numerically
_locationset.sort(function (a, b) {
return ((a.Distance < b.Distance) ? -1 : ((a.Distance > b.Distance) ? 1 : 0));
});
// take "N" closest shops
_locationset = _locationset.slice(0, settings.storeLimit);
//Check the closest marker
if (_locationset[0].Distance > settings.distanceAlert) {
handleError("Unfortunately, our closest location is more than " + settings.distanceAlert + " miles away.");
}
//Create the map with jQuery
$(function () {
var orig_LatLng = new google.maps.LatLng(orig_lat, orig_lng);
//Google maps settings
var myOptions = {
center: orig_LatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(settings.mapDiv), myOptions);
//Create one infowindow to fill later
var infowindow = new google.maps.InfoWindow();
//Add user location marker
var marker = createUserMarker(orig_LatLng, "0", settings.startPinColor);
marker.setAnimation(google.maps.Animation.DROP);
var bounds = new google.maps.LatLngBounds();
bounds.extend(orig_LatLng);
$("#" + settings.listDiv).empty();
$(_locationset).each(function (i, location) {
bounds.extend(location.LatLng);
letter = String.fromCharCode("A".charCodeAt(0) + i);
location.Marker = createMarker(location.LatLng, letter, settings.pinColor);
create_infowindow(location);
listClick(letter, location);
});
// zoom in/out to show all markers
map.fitBounds(bounds);
function listClick(letter, shop) {
$('<li />').html("<div class=\"list-details\">"
+ "<div class=\"list-label\">" + letter + "<\/div><div class=\"list-content\">"
+ "<div class=\"loc-name\">" + shop.Name + "<\/div> <div class=\"loc-addr\">" + shop.Description + "<\/div>"
+ (shop.Distance ? "<div class=\"loc-addr2\"><i>approx. " + shop.Distance + " " + ((shop.Distance == 1) ? "mile" : "miles" ) + "</i><\/div>" : "")
+ "<div class=\"loc-web\"><a href=\"http://maps.google.co.uk/maps?saddr="
+ formatGoogleMapUrlString($("#address").val()) + "+%40" + orig_lat + "," + orig_lng
+ "&daddr=" + formatGoogleMapUrlString(shop.Name) + "+%40" + shop.LatLng.lat() + "," + shop.LatLng.lng()
+ "&hl=en" + "\" target=\"_blank\">ยป Get directions</a><\/div><\/div><\/div>")
.click(function () {
create_infowindow(shop, "left");
}).appendTo("#" + settings.listDiv);
};
//Custom marker function - aplhabetical
function createMarker(point, letter, pinColor) {
//Set up pin icon with the Google Charts API for all of our markers
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" + letter + "|" + pinColor + "|" + settings.pinTextColor,
new google.maps.Size(21, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34));
var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
new google.maps.Size(40, 37),
new google.maps.Point(0, 0),
new google.maps.Point(12, 35));
//Create the markers
return new google.maps.Marker({
position: point,
map: map,
icon: pinImage,
shadow: pinShadow,
draggable: false
});
};
//Custom marker function - aplhabetical
function createUserMarker(point, letter, pinColor) {
//Set up pin icon with the Google Charts API for all of our markers
var pinImage = new google.maps.MarkerImage("images/green_pin.png");
//Create the markers
return new google.maps.Marker({
position: point,
map: map,
title: "Your Location",
icon: pinImage,
draggable: false
});
};
//Infowindows
function create_infowindow(shop, listLocation) {
//Is the distance more than one mile?
if (shop.Distance == 1) {
var mi_s = "mile";
} else {
var mi_s = "miles";
}
var formattedAddress = "<div class=\"infoWindow\"><b>" + shop.Name + "<\/b>"
+ "<div>" + shop.Description + "<\/div>"
+ (shop.Distance ? "<div><i>" + shop.Distance + " " + mi_s + "<\/i><\/div><\/div>" : "<\/div>");
//Opens the infowindow when list item is clicked
if (listLocation == "left") {
infowindow.setContent(formattedAddress);
infowindow.open(shop.Marker.get(settings.mapDiv), shop.Marker);
}
//Opens the infowindow when the marker is clicked
else {
google.maps.event.addListener(shop.Marker, 'click', function () {
infowindow.setContent(formattedAddress);
infowindow.open(shop.Marker.get(settings.mapDiv), shop.Marker);
})
}
};
});
}
});
}
});
});
}
});
};
})(jQuery);
Under var settings I need xmlLocation to be the dynamically geolocated URL. It seems the variable is not being set correctly. I get an undefined error message when I try to call LocationGlobal. I have speculated on this issue and have hit a dead end with it. Any help is greatly appreciated. Thanks.
The alert shows undefined because of the callback nature of the getCurrentLocation() operation. You have to call the LocationGlobal dependent function from inside the callback function of the getCurrentLocation() operation. probably like,
navigator.geolocation.getCurrentPosition(function(position)
{
var lat = position.coords.latitude;
var lon = position.coords.longitude;
LocationGlobal = 'data/gen_default_map.php?lat=' + lat + '&lng=' + lon + '&radius=30';
alert(LocationGlobal);
$('#map').storeLocaor({ mapDiv: 'map', xmlLocation: LocationGlobal }); //Just an example
});
hope this helps.

Google Map API - Get Address of User

Ive tried several methods to get get a visitors country location using geolocation method but im stil at no avail.
Could someone help atall as I'd like to get a visitors country and write it to a database using ajax.
my current code
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
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)
var country = results[7].formatted_address;
$('.location').text(country);
var dataStrings = 'email=<?php echo $userid;?>&location='+ country;
console.log(dataStrinsg);
$.ajax({
type: "POST",
url: "location-update.php",
data: dataStrings,
success: function() {
location.reload();
}
});
return false;
if (results[1]) {
//formatted address
// alert(results[0].formatted_address)
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}</script>
Assuming that you call initalize() before the geocoding(otherwise geocode will be undefined):
You're accessing results[7] here:
var country = results[7].formatted_address;
...but there is no guarantee that results[7] exists.

Categories