How can I get lat/lang with Geocode? - javascript

I have an address, and now I need to retrieve the Lat / Lang coordinates.
At Google, they only have good examples for V2 and not V3.
I want to do the following:
var myLatLAng = getLatLang(adress);
How can I modify this code to make that happend?
function showAddress(address) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(address);
}
}
);
}

You cannot return any value because getLatLng is using callback function so it can only interact with your enviroment.
You can assign it to some other variable
var lat, lng;
function showAddress(address) {
...
} else {
lat = point.lat();
lng = point.lng();
orExecuteOtherfunction();
}
}
Or execute some other function that will do something with your returned point.

Related

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;

How to get address from lat and lng?

I have two set of lat and lng.
I want both address and stored in some variable:
var geocoder = new google.maps.Geocoder();
for(var i=0; i<json_devices.length; i++)
{
var lat = json_devices[i].latitude;
var lng = json_devices[i].longitude;
console.log(lat);
console.log(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]) {
address=results[1].formatted_address;
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
console.log(address);
}
In this, lat & lan get correctly. But address are not stored in variable. What is the mistake?
I am using this method and it is working perfect for me.
Please have a look on it.
public String getAddressFromLatLong(GeoPoint point) {
String address = "Address Not Found";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
address =addresses.get(0).getAddressLine(0);
if(address.length()<=0)
address =addresses.get(0).getSubLocality();
}
}
catch (Exception e) {
e.printStackTrace();
}
return address;
}
Here the Google geocode is asynchonous type of function call.
From DOCS:
Accessing the Geocoding service is asynchronous, since the Google Maps
API needs to make a call to an external server. For that reason, you
need to pass a callback method to execute upon completion of the
request. This callback method processes the result(s). Note that the
geocoder may return more than one result.
So you can't get the address like that, instead use the common approach called callback.
Here I have created a sample code to explain the process, which can be altered by yourself.
var geocoder;
function codeLatLng(callback) {
geocoder = new google.maps.Geocoder();
var input = document.getElementById("latlng").value;
var latlngStr = input.split(",", 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
address = results[1].formatted_address;
callback(address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
$('input[type="button"]').on('click', function () {
codeLatLng(function (address) { //function call with a callback
console.log(address); // THE ADDRESS WILL BE OBTAINED
})
});
JSFIDDLE

Prohibit looping functions

Function onSuccess runs indefinitely, as constantly asks the coordinates from the GPS receiver. It contains a function createMap, to be performed only once. How is this achieved? Make a function outside the function also can not, because it is passed as a parameter value of a variable of the function.
watchID = navigator.geolocation.watchPosition(function(position) {onSuccess(position, arrMyLatLng);}, onError, options);
function onSuccess(position, arrMyLatLng)
{
var latitude , longitude ;
latitude = position.coords.latitude ;
longitude = position.coords.longitude;
var myLatLng = new google.maps.LatLng(latitude, longitude);
createMap(myLatLng, arrMyLatLng);// This feature will run for an indefinite number of times. It is only necessary once.
map.panTo(myLatLng) ;
}
You can create a function with private state using a closure:
onSuccess = (function() {
var created = false;
return function (position, arrMyLatLng) {
var latitude , longitude ;
latitude = position.coords.latitude ;
longitude = position.coords.longitude;
var myLatLng = new google.maps.LatLng(latitude, longitude);
if (!created) {
createMap(myLatLng, arrMyLatLng);
created = true;
}
map.panTo(myLatLng) ;
};
}());
Function that runs only once:
function runOnce() {
if (runOnce.done) {
return;
} else {
// do my code ...
runOnce.done = true;
}
}
Because function is object in JavaScript, you may set a property on it.
Assuming createMap returns a map
var map = null;
function onSuccess(position, arrMyLatLng) {
var latitude = position.coords.latitude ;
var longitude = position.coords.longitude;
var myLatLng = new google.maps.LatLng(latitude, longitude);
map = map || createMap(myLatLng, arrMyLatLng);
map.panTo(myLatLng);
}
createMap will only run if map evaluates to "false" (i.e. is null), thus createMap only runs once.

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.

Print out coordinates from a geocoding script

I want to print out the coordinates calculated by a geocoding javascript ( maded with Google api V3 ), how can i do that??
and then, how can i pass this values to two variables ($Lat and $Long) that are in a php file that generate a google map maded in Api V2 ??
thanks.
this is my javascript code:
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=HERE MY API KEY" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="http://code.google.com/apis/gears/gears_init.js"></script>
<script type="text/javascript">
function getLocale(){
if ( navigator ) {
if ( navigator.userLanguage ) {
return navigator.userLanguage.toLowerCase();
}
else if ( navigator.language ) {
return navigator.language.toLowerCase();
}
else if ( navigator.browserLanguage ) {
return navigator.browserLanguage.toLowerCase();
}
else if ( navigator.systemLanguage ) {
return navigator.systemLanguage.toLowerCase();
}
}
return "unknown";
}
var locales = new Object();
locales["en-gb"] = {lat:54.559322587438636, lng:-4.1748046875, location:"United Kingdom"};
locales["en-us"] = {lat:38.41055825094609, lng:-100.37109375, location:"USA"};
// TODO - more locales
function showMap(latLong, zoom){
var options = {
zoom: zoom,
center: latLong,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), options);
var marker = new google.maps.Marker({
position: latLong,
map: map,
title:"Your location"
});
}
function TryGoogleLoader(){
if (google.loader.ClientLocation != null) {
var address = google.loader.ClientLocation.address;
var yourLocation = address.city + ", " + address.region + ", " + address.country;
document.getElementById("location").innerHTML = "Your location (using Google loader) is " + yourLocation;
var latLong = new google.maps.LatLng(google.loader.ClientLocation.latitude,
google.loader.ClientLocation.longitude);
showMap(latLong, 12);
}
else {
// map locale to location
var locale = getLocale();
if (locales[locale] != null) {
var latLong = new google.maps.LatLng(locales[locale].lat, locales[locale].lng);
document.getElementById("location").innerHTML =
"Guessing your location based on your locale - " + locales[locale].location;
showMap(latLong, 5);
}
else {
document.getElementById("location").innerHTML = "Your location can not be found - locale is " + locale;
}
}
}
function TryGoogleGears(){
if (google.gears) {
// Try Google Gears Geolocation
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
var latLong = new google.maps.LatLng(position.latitude, position.longitude);
document.getElementById("location").innerHTML = "Found location via Google Gears";
showMap(latLong, 15);
}, function() {
TryGoogleLoader();
});
}
else
TryGoogleLoader();
}
window.onload = function() {
// try W3C standard approach
var geoTimeout = 10000;
var timeOuthandler = setTimeout("TryGoogleGears()", geoTimeout);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
clearTimeout(timeOuthandler);
var latLong = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
document.getElementById("location").innerHTML = "Found location via W3C standard";
showMap(latLong, 15);
}, function() {
// something went wrong, try Google Gears
clearTimeout(timeOuthandler);
TryGoogleGears();
}, {timeout:geoTimeout});
}
else
TryGoogleGears();
}
</script>
how can i print with an alert code the value of the "var latLong"?
how can i pass this value to a set of php variables like $lat and $long?
thanks.
On the W3C function you could do this on success
document.getElementById("location").innerHTML = position.coords.latitude +", "+position.coords.longitude;
On the TryGoogleGears function you could do this on success
document.getElementById("location").innerHTML = position.latitude +", "+position.longitude;
In order to pass the LatLong pair back to PHP you will need to use a XMLHTTPRequest or something similar. This is because PHP is a server side script that executes before JavaScript does, which runs on the client. So to tell PHP something you need to either load a new page and pass the data from JavaScript to PHP with headers, GET, or POST variables. You can either load this page the normal way in the browser and your users see a redirect or you can load it in the background using XMLHTTPRequest.

Categories