I don\'t have any previous javascript experience.
I\'m trying to implement the following function which I wish to use to return the values lat and lng:
f
Declare variables lat
and lng
outside callback function.
In header section add google library:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
correct syntax errors and then start the function: DEMO
CODE (with jquery onload):
var lat = "";
var lng = "";
function getLatLng(callback) {
lat = callback.lat();
lng = callback.lng();
alert(lat +" "+lng);
}
$(function() {
var geocoder = new google.maps.Geocoder()
geocoder.geocode({
address: "SE-17270 Sverige"
}, function(locResult) {
getLatLng(locResult[0].geometry.location);
});
});
you could use global variables or return the values in an array for instance:
global variables method:
lat = "";
lng = "";
function get_address() {
var geocoder = new google.maps.Geocoder()
geocoder.geocode({ address: "SE-17270 Sverige"},
function(locResult) {
lat = locResult[0].geometry.location.lat();
lng = locResult[0].geometry.location.lng();
alert(lat);
alert(lng);
})
}
array method:
function get_address() {
var geocoder = new google.maps.Geocoder()
geocoder.geocode({ address: "SE-17270 Sverige"},
function(locResult) {
var lat = locResult[0].geometry.location.lat();
var lng = locResult[0].geometry.location.lng();
thearray = [];
thearray.push(lat);
thearray.push(lng);
return thearray;
})
}
Use a callback to handle the geocoding results:
function myCallback(lat, lng) {
// Process lat and lng.
}
function get_address(callback) {
var geocoder = new google.maps.Geocoder()
geocoder.geocode({ address: "SE-17270 Sverige"},
function(locResult) {
var lat = locResult[0].geometry.location.lat();
var lng = locResult[0].geometry.location.lng();
callback(lat, lng);
}
);
}
....
get_address(myCallback);