Accessing longitude, latitude outside the geocode() function [duplicate] - google-maps

This question already has answers here:
How do I return a variable from Google Maps JavaScript geocoder callback?
(5 answers)
Closed 7 years ago.
When I use the code below its alerting a blank value? why is that?
HTML
<body onload="initialize()">
<div id="map_canvas" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Encode" onclick="display()">
</div>
</body>
JavaScript
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
var loc=[];
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
loc[0]=results[0].geometry.location.lat();
loc[1]=results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
return loc;
}
function display(){
var long_lat=codeAddress();
alert(long_lat);
}

because your function codeAddress is executed, assigning empty array to loc, executing asynchronous request to google geocoder and returns loc, which is empty, because its real value is assigned when response from google comes. In other words, allert should be inside response handler:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
var loc=[];
// next line creates asynchronous request
geocoder.geocode( { 'address': address}, function(results, status) {
// and this is function which processes response
if (status == google.maps.GeocoderStatus.OK) {
loc[0]=results[0].geometry.location.lat();
loc[1]=results[0].geometry.location.lng();
alert( loc ); // the place where loc contains geocoded coordinates
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
// pretty meaningless, because it always will be []
// this line is executed right after creating AJAX request, but not after its response comes
return loc;
}
function display(){
codeAddress();
}
this is how AJAX works... process results in callback handlers.
if you want to separate geocoding and 'dispalying' you can execute display function inside handler:
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var loc=[]; // no need to define it in outer function now
loc[0]=results[0].geometry.location.lat();
loc[1]=results[0].geometry.location.lng();
display( loc );
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function display( long_lat ){
alert(long_lat);
}
html:
<input type="button" value="Encode" onclick="codeAddress()">
you can make it even more generic, if you will geocode not only to display. Then you can define callback as parameter to codeAddress function:
function codeAddress( callback ) {
...
geocoder.geocode( { 'address': address}, function(results, status) {
...
callback( loc ); // instead of dispaly( loc );
...
}
...
}
codeAddress( display ); // to execute geocoding

Related

Google Maps API Geocode - return GPS coordinations [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've got this code:
var get_lat = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lat is: '+ results[0].geometry.location.lat());
return results[0].geometry.location.lat();
}
});
}
var get_lng = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lng is: '+ results[0].geometry.location.lng());
return results[0].geometry.location.lng();
}
});
}
In console it prints the coordinates I need, but the return value is always undefined:
I use it in classic initialize for Google Maps like this:
function createMarker(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
}
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(49.210366,15.989588)
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
var gps_lat = get_lat(address);
var gps_lng = get_lng(address);
console.log('GPS lat: ' + gps_lat); // logs "undefined"
console.log('GPS lng: ' + gps_lng); // logs "undefined"
var marker = createMarker({lat: gps_lat}, lng: gps_lng});
}
$(window).on("load", function (e) {
initialize();
});
Do you have any idea why the function consoles the right value but it doesn't return anything?
For GMAP API I use this script: http://maps.google.com/maps/api/js?sensor=false&libraries=geometry
You have the return inside an anonymous function that you pass to geocoder.geocode, all in yet another function (get_lat/get_lng). get_lat/get_lng themselves don't have a return statement, and thus return undefined.
Furthermore, geocoder.geocode will call your anonymous function asynchronously. Which means that there is no chance for get_lat/get_lng to get hold of the return value and return it where get_lat/get_lng was called.
One solution (the simplest one) is to put the createMarker code in the callback for geocoder.geocode. Also, in this case you will have to merge your two get_lat/get_lng functions. Example:
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var gps_lat = results[0].geometry.location.lat()
var gps_lng = results[0].geometry.location.lng();
console.log('lat is ' + gps_lat + '. lng is ' + gps_lng);
var marker = createMarker({lat: gps_lat, lng: gps_lng});
return results[0].geometry.location.lat();
}
});
You have to wait until Google API gives response. So write a logic to create marker in callback function of Google API as shown below.
var getLatLng = function (address)
{
geocoder.geocode({ 'address': address }, function (results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var location = results[0].geometry.location;
// Create marker once you get response from Google
createMarker({ lat: location.lat(), lng: location.lng() });
}
});
}
and call that function as shown below
function initialize()
{
var myOptions =
{
zoom: 8,
center: new google.maps.LatLng(49.210366, 15.989588)
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
// Old code ------------------------------------------------
//var gps_lat = get_lat(address);
//var gps_lng = get_lng(address);
//console.log('GPS lat: ' + gps_lat); // logs "undefined"
//console.log('GPS lng: ' + gps_lng); // logs "undefined"
//var marker = createMarker({ lat: gps_lat, lng: gps_lng });
// ----------------------------------------------------------
// New code
getLatLng(address);
}
and you will get marker on a map

Getting coordinates based on city name google map

I am trying to create coordinates based on city with google maps, here is example what i have for now, i always get error?
var address = 'Zurich, Ch';
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var Lat = results[0].geometry.location.lat();
var Lng = results[0].geometry.location.lng();
} else {
alert("Something got wrong " + status);
}
});
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(Lat, Lng),
};
The geocoder is asynchronous. You need to use the returned data in the callback function when/where it is available.
related question: Using Address Instead Of Longitude And Latitude With Google Maps API
proof of concept fiddle
code snippet:
function initialize() {
var address = 'Zurich, Ch';
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var Lat = results[0].geometry.location.lat();
var Lng = results[0].geometry.location.lng();
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(Lat, Lng)
};
var map = new google.maps.Map(
document.getElementById("map_canvas"), myOptions);
} else {
alert("Something got wrong " + status);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

Zooming and centering the geocoded place using google maps api

I am working with the google maps api for one of my application. I have a textbox in which the user enters place name. It should geocode the users place name given in the textbox and zoom and center to that geocoded place name. I am successful in the geocoding but zooming and centre is not as expected. The code and output snapshot is provided.The black rectangle in the image is the place name that was geocoded based on the user input in the textbox. But zooming and centering is somewhere in the corner of the map. I want it to make the geocoded place name in the center of map.
var mapProp = {
center: x,
zoom: 4,
disableDefaultUI: true,
mapTypeId: layer,
mapTypeControlOptions: {
mapTypeIds: [layer]
}
};
var map = new google.maps.Map(document.getElementById("googlemaps"), mapProp);
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
map.mapTypes.set(layer, new google.maps.StamenMapType(layer));
geocoder.geocode({
'address': place_name_filter
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert(place_name_filter + " not found");
console.log("status : ", status);
}
});
Place_name_filter is the variable which holds the the place name entered in the textbox.
Output_Snapshot_for_the_above_code
Expected_Output
To zoom to a result from the geocoder use map.fitBounds and the .geometry.viewport (or geometry.bounds) LatLngBounds in the response.
code snippet:
function initialize() {
var mapProp = {
center: {
lat: 25,
lng: -90
},
zoom: 4,
};
var map = new google.maps.Map(document.getElementById("googlemaps"), mapProp);
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
var place_name_filter = "Abilene, TX";
geocoder.geocode({
'address': place_name_filter
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert(place_name_filter + " not found");
console.log("status : ", status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#googlemaps {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googlemaps"></div>

Google Maps API v3 multiple markers Infowindow

I've used the code below to display a map with multiple markers and infowindows. Now I have encountered the very common problem of the last infowindow showing up on all markers. I've tried all sorts of solutions including: http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/ and this one http://www.robertbolton.com/blog/google-maps-v3-multiple-markers-and-infowindows-in-a-loop but none of them fix the problem.
Here is my code:
var infowindow = null;
var geocoder;
var map;
$(document).ready(function() {
initialize();
});
function initialize() {
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
setMarkers(map, people);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
}
var people = [
{"userid":"47","lastname":"lastname1","firstname":"firstname1","address":"Paris, France","phone1":"00000000000","phone2":"","email":"me#me.com"},
{"userid":"42","lastname":"lastname2","firstname":"firstname2","address":"Versaille, France","phone1":"0","phone2":"0","email":"me#me.com"}
];
function setMarkers(map, people) {
for (var i = 0; i < people.length; i++) {
var p = people[i];
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': p["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
html: p["address"]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
geocoding is an asynchronous request. So when you use geocoding inside the for-loop, the loop is already finished when you receive the results, i will always be 1 and point to the last item of people.
What you can do: split the marker-creation into 2 functions. 1 for the loop which calls the 2nd function that creates the markers:
remove the current function setMarkers and add the following 2 functions to your script:
function setMarkers(map,people) {
for (var i = 0; i < people.length; i++) {
setMarker(map, people[i])
}
}
function setMarker(map, people) {
var p=people;
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': p["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
html: p["address"]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
The rest of your script may stay as it is.

Google Maps API V3 and Local search problem - empty results?

I am trying to implement a Maps API V3 and Local Search but I seem to be having problems. Somehow, the results in the OnLocalSearch() function is empty.
Here is my complete code:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
// do stuff when DOM is ready
var geocoder = new google.maps.Geocoder();
var address = '{{string_location}}';
var map;
// Our global state for LocalSearch
var gInfoWindow;
var gSelectedResults = [];
var gCurrentResults = [];
var gLocalSearch = new GlocalSearch();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//alert(results[0].geometry.location.lat())
//alert(results[0].geometry.location.lng())
//Create the Map and center to geocode results latlong
var latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
gLocalSearch.setSearchCompleteCallback(this, OnLocalSearch);
gLocalSearch.execute("{{business_item.name}}");
}
else {
alert('No results found. Check console.log()');
console.log("Geocoding address: " + address);
console.log("Geocoding failed: " + status);
}
});
}
/*
Other functions
*/
function OnLocalSearch() {
if (gLocalSearch.results[0]) { //This is empty. Why?
var resultLat = gLocalSearch.results[0].lat;
var resultLng = gLocalSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
callbackFunction(point);
}else{
alert("not found!");
}
}
});
//]]>
</script>
FYI, I am using this as an example and I am stuck for a few hours now about this: http://gmaps-samples-v3.googlecode.com/svn-history/r136/trunk/localsearch/places.html
Any reply will be greatly appreciated.
Regards,
Wenbert
UPDATE
I made a mistake somewhere here:
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0" type="text/javascript"><;/script>
<script src="http://maps.google.com/maps/api/js?v=3.1&sensor=false&region=PH"></script>
Also, make sure you double check the address you are geocoding. I am from the Philippines and it seems that Google only geocodes Major Roads. See http://gmaps-samples.googlecode.com/svn/trunk/mapcoverage_filtered.html
Thanks to jgeerdes from irc.geekshed.net #googleapis
Just making a couple of tweaks so that the code is actually complete, and using an address I know will be geocoded successfully plus a query I know will return something, your code works. Here is what I did:
<html>
<head>
<title>Wenbert test</title>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
//<![CDATA[
google.load('jquery','1.4.2');
google.load('maps','3',{other_params:'sensor=false'});
google.load('search','1');
alert('starting...');
$(document).ready(function() {
alert('here');
// do stuff when DOM is ready
var geocoder = new google.maps.Geocoder();
var address = '4019 lower beaver rd. 50310';
var map;
// Our global state for LocalSearch
var gInfoWindow;
var gSelectedResults = [];
var gCurrentResults = [];
var gLocalSearch = new GlocalSearch();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//alert(results[0].geometry.location.lat())
//alert(results[0].geometry.location.lng())
//Create the Map and center to geocode results latlong
var latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
gLocalSearch.setSearchCompleteCallback(this, OnLocalSearch);
gLocalSearch.execute("debra heights wesleyan church");
}
else {
alert('No results found. Check console.log()');
console.log("Geocoding address: " + address);
console.log("Geocoding failed: " + status);
}
});
}
/*
Other functions
*/
function OnLocalSearch() {
if (gLocalSearch.results[0]) { //This is empty. Why?
var resultLat = gLocalSearch.results[0].lat;
var resultLng = gLocalSearch.results[0].lng;
var point = new google.maps.LatLng(resultLat,resultLng);
callbackFunction(point);
}else{
alert("not found!");
}
}
});
//]]>
</script>
</head>
<body>
<div id="map_canvas" style="height:100%;"></div>
</body>
</html>