I'm trying to use the Geocode API in a while loop and having no luck. It seems that my if statement inside my while loop is not evaluating until the end of the while loop. I am wondering if it is because of the Geocode API needs time to respond but I can't seem to get it to evaluate correctly. Here is my code:
while (posts != j)
{
var image = server + '/location_marker.png';
//var myLatLng = new google.maps.LatLng(locationLat[j],locationLong[j]);
var address = addressGlobal[j];
myLatLng = 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 myLatLng = new google.maps.LatLng(lat,lng);
alert(lat + lng);
return myLatLng;
}
else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
alert(myLatLng);
place[j] = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
url: postURL[j],
title: postTitle[j]
});
google.maps.event.addListener(place[j], 'click', function() {
map.panTo(this.getPosition());
map.setZoom(7);
$("#fountainG").fadeIn(250);
history.pushState(null, this.title, this.url);
//offsetCenter(myLatLng,-400,0,map);
$(".dynamic").load(this.url + " .dynamic", function(response, status, xhr) {
$('.dynamic').fadeIn(500);
$('.dim').fadeIn(500);
$("#fountainG").fadeOut(250);
});
});
j++;
}
I think I've found the answer and it appears to be to do with closures. I'm not entirely sure how it fixed it, but I moved the geocoding functions into a nested function and then I call it within the while loop. Since it doesn't execute until the end, once it does, I need to loop through the arrays again and add them to a map. The code works successfully, but I don't really understand why, unfortunately.
I'd love if someone could chime in on why this works and perhaps a better way to set it up, but for the meantime this is fixed with:
function initialize() {
function geocode() {
var address = addressGlobal[j];
var k = 0;
myLatLng = geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
while (k != posts)
{
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var myLatLng = new google.maps.LatLng(lat,lng);
alert(lat + lng);
place[k] = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
url: postURL[k],
title: postTitle[k]
});
google.maps.event.addListener(place[k], 'click', function()
{
map.panTo(this.getPosition());
map.setZoom(7);
$("#fountainG").fadeIn(250);
history.pushState(null, this.title, this.url);
//offsetCenter(myLatLng,-400,0,map);
$(".dynamic").load(this.url + " .dynamic", function(response, status, xhr)
{
$('.dynamic').fadeIn(500);
$('.dim').fadeIn(500);
$("#fountainG").fadeOut(250);
});
});
k++;
}
}
else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
var geocoder = new google.maps.Geocoder();
google.maps.visualRefresh = true;
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(37.09024,-95.712891),
disableDefaultUI: true,
};
var posts = locationLat.length;
var j = 0;
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var place = [];
while (posts != j)
{
var image = server + '/location_marker.png';
//var myLatLng = new google.maps.LatLng(locationLat[j],locationLong[j]);
geocode();
alert(myLatLng);
j++;
}
//Determine if the user came in via the front page or a post so we can set the viewport correctly
if ( entryPage == "post" )
{
map.setZoom(7);
var postView = new google.maps.LatLng(postLocationLat, postLocationLong);
map.panTo(postView);
}
}
Related
I need some advice or a telling off because my code is wrong. I'm new to JQuery and google maps api. I have a JSON get to retrieve my data. I have declared an array and stored (hopefully this is the correct way to do this).
update** - Thanks to #geocodezip I have updated my code to allow correct population of array.
When I run my application the map loads fine but no markers.
I have changed my Google maps initializeMap() to the asynchronous version
function initializeMap() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
zoom: 12,
center: new google.maps.LatLng(citylat, citylng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < carparksArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(carparksArray[i][1], carparksArray[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(carparksArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
My array in console.log image
I now have an array populated, but still no markers on my map.
This is my whole script. Maybe there are some major flaws.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//define variables
var geocoder;
var citylat = 0;
var citylng = 0;
var carparksArray = [];
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();
}
//get city of current location and runs codeAddress()
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 arrAddress = results;
console.log(results);
$.each(arrAddress, function (i, address_component) {
if (address_component.types[0] == "postal_town") {
itemPostalTown = address_component.address_components[0].long_name;
document.getElementById("town").value = itemPostalTown;
codeAddress();
}
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
//get latlong of city and runs getCarParks()
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("town").value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
citylat = results[0].geometry.location.lat();
citylng = results[0].geometry.location.lng();
getCarParksLatLng();
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
//sets map up
function initializeMap() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
zoom: 12,
center: new google.maps.LatLng(citylat, citylng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < carparksArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(carparksArray[i][1], carparksArray[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(carparksArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
//loads map
function loadScript() {
var script = document.createElement("script");
script.src = "http://maps.googleapis.com/maps/api/js?callback=initializeMap";
document.body.appendChild(script);
}
//get carparks names
function getCarParksLatLng() {
var town = document.getElementById("town").value;
var carparkList = "<p>";
var uri = "http://localhost/api/carparks?$filter=Town%20eq%20%27" + town + "%27";
$.getJSON(uri,
function (data) {
carparksArray = [];
$('#here_data').empty(); // Clear existing text.
// Loop through the list of carparks.
$.each(data, function (key, val) {
carparksArray.push([val.Name, val.Latitude, val.Longitude]);
});
console.log(carparksArray);
});
loadScript();
}
$(document).ready(initialize)
</script>
You are not adding the entries to the carparkArray correctly. Each array element needs to be an array, so the array looks like this:
var carparksArray = [
['Bondi Beach', -33.890542, 151.274856, 4],
// ...
];
updated code:
var carparks = [];
$.getJSON(uri,
function (data) {
$('#here_data').empty(); // Clear existing text.
// Loop through the list of carparks.
$.each(data, function (key, val) {
carparks.push([val.Name, val.Latitude, val.Longitude]);
});
});
loadScript();
}
proof of concept fiddle
Thanks for everyone's help on this. Because #geocodezip stated that
$.getJSON is asynchronous I moved my loadscript() function call inside the getJSON function and it now plots the map points.
$.getJSON(uri,
function (data) {
carparksArray = [];
$('#here_data').empty(); // Clear existing text.
// Loop through the list of carparks.
$.each(data, function (key, val) {
carparksArray.push([val.Name, val.Latitude, val.Longitude]);
});
console.log(carparksArray);
loadScript();
});
I have the following code to display markers on a google map based upon an array of locations, however I have a mix of postcodes and Lat/longs, I've used the geocoder to convert the postcodes to lat/longs but can't then use them when I try and set a marker.
Thanks for any help!
var geocoder;
var map;
var pos;
var geoLat;
var geoLong;
var markers = [];
var bounds = new google.maps.LatLngBounds();
var locations = [
[null, 'London Eye, London', 51.503454,-0.119562, 4]
,[null, 'Palace of Westminster, London', 51.499633,-0.124755]
,[null, 'The London Dungeon', 'SE1 7PB', , 2] //Value with Postcode
];
function isNumber(o) { return ! isNaN (o-0) && o !== null && o !== "" && o !== false; }
function init() {
geocoder = new google.maps.Geocoder();
var num_markers = locations.length;
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(locations[0][2], locations[0][3]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var i = 0; i < num_markers; i++) {
if (isNumber (locations[i][2]) && isNumber (locations[i][3])){
geoLat = locations[i][2]
geoLng = locations[i][3]
alert(typeof(geoLat) +' '+typeof(geoLng)) //generates a correct number number response
}else{
geocoder.geocode( { 'address': locations[i][2]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
geoLat = results[0].geometry.location.lat()
geoLng = results[0].geometry.location.lng()
alert(typeof(geoLat) +' '+typeof(geoLng)) //generates a correct number number response
}
});
}
pos = new google.maps.LatLng(geoLat, geoLng); // Doesn't get value if a geocodes postcode added in
bounds.extend(pos);
map.fitBounds(bounds);
markers[i] = new google.maps.Marker({
position: pos,
map: map,
id: i,
title: locations[i][1]
});
}
}
google.maps.event.addDomListener(window, 'load', init);
The Geolocation request is an async call, which means that your script is running through while the API request isnĀ“t finished yet.
Therefore you have two options.
Define the marker directly in the callback function
if (status == google.maps.GeocoderStatus.OK) { }
Or write sth. like a setMarker() function and call it in the callback.
function setMarker(lat, lng){}
In general it is a good practice to also make the Geocoding request a function, like:
doGeocode: function (address, postal_code, callback) {
console.log("TEST: " + address.toString());
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address,
'componentRestrictions': {
'postalCode': postal_code,
'country': 'de'
}
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
console.log(results);
callback(results);
} else {
//Error handling
alert('Geocode was not successful for the following reason: ' + status);
}
});
if you want to call it now just do
doGeocode (adress, postal_code, function (response){
//do your stuff
)};
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
google.maps.event.addDomListener(window, 'load', initialize);
var _map;
var _originMarker, _destinationMarker;
var _geocoder;
function initialize()
{
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(21.1289956,82.7791754)
};
_map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
_geocoder = new google.maps.Geocoder();
_originMarker=createMarker('search-from');
_destinationMarker=createMarker('search-to');
google.maps.event.addListener(_map, 'click', function(mouseEvent)
{
if ((_activeMarker != null) && (!_activeMarker.getMap())) placeMarker(_activeMarker, mouseEvent.latLng);
});
}
function createMarker(_autoComplId)
{
var _autoCompl = document.getElementById(_autoComplId);
var _newmarker = new google.maps.Marker({
position: new google.maps.LatLng(0, 0),
draggable: true,
map: null,
autoCompl: _autoCompl
});
google.maps.event.addListener(_newmarker, "dragend", function(event)
{
placeMarker(_newmarker, _newmarker.getPosition());
});
var _autocomplete = new google.maps.places.Autocomplete(_autoCompl);
_autocomplete.setTypes(['geocode']);
google.maps.event.addListener(_autocomplete, 'place_changed', function()
{
var _place = _autocomplete.getPlace();
if (_place.geometry == null) return;
setCenterAndZoom(_place.geometry.location, 16);
placeMarker(_newmarker, _place.geometry.location);
});
return _newmarker;
}
function placeMarker(_marker, _location)
{
_marker.setPosition(_location);
RenewAddress(_marker);
}
function RenewAddress(_marker)
{
_geocoder.geocode({'latLng': _marker.getPosition()}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
if (_marker.getMap() == null) _marker.setMap(_map);
_marker.autoCompl.value = results[0].formatted_address;
}
});
}
function setCenterAndZoom(_center, _zoom)
{
_map.setCenter(_center);
_map.setZoom(_zoom);
}
var _activeMarker = null;
function setActiveMarker(index)
{
switch(index)
{
case 0:
_activeMarker = _originMarker;
break;
case 1:
_activeMarker = _destinationMarker;
}
}
</script>
this is what im using to retrieve address,
and now i want to retrieve latitude and longitude along with my
address, in the above function RenewAddress(_marker)
iam using the _geocoder.geocode({'latLng': _marker.getPosition()}, function(results, status)
but iam unable to retrieve it i just got the result of the address
auto filled in the text box as an output but iam unable to retrieve
latitude and longitude
My version of RenewAddress() function is almost the same as your except that I retrieve lat/lng values before and show them in console.
function RenewAddress(_marker) {
console.log('RenewAddress');
var latlng = _marker.getPosition();
console.log(latlng.lat());
console.log(latlng.lng());
_geocoder.geocode({'latLng': _marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('status ok');
if (_marker.getMap() == null)
_marker.setMap(_map);
_marker.autoCompl.value = results[0].formatted_address;
console.log(results[0].formatted_address);
console.log(_marker.autoCompl.value);
var exactAddress = document.getElementById('search-to');
exactAddress.value = _marker.autoCompl.value + ', lat/lng: ' + latlng.lat() + ':' + latlng.lng();
} else {
console.log('error: ' + status);
}
});
}
See example at jsbin with only one marker and latitude and longitude fields. Write something to town/city/country field, for example Odisha. Select it. After that marker should be shown, exact address should be set and latitude and longitude fields. If you move marker around, information will be changed.
I have edited my code below and put the full JS. I am trying to extract a list of places near a given zipcode or city. My first step would be to take the zipcode or city name and get the latlng coordinates and then get the list of places. I am getting the following errors "Cannot call method 'geocode' of undefined " & " Cannot read property 'offsetWidth' of null" Any help will be greatly appreciated.
var placesList;
var geocoder;
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map'));
geocoder = new google.maps.Geocoder();
}
function getLatLng(address, callback) {
geocoder.geocode({
address: address
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var location = new google.maps.LatLng(result.lat(), result.lng());
map.setCenter(location);
var marker = new google.maps.Marker({
map: map,
position: location
});
callback(location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
getLatLng('14235', function (latLngLocation) {
var pyrmont = latLngLocation;
var request = {
location: pyrmont,
radius: 5000,
types: ['park', 'zoo']
};
placesList = document.getElementById('places');
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
var request1 = {
reference: place.reference
};
service.getDetails(request1, createMarkers);
function callback(results, status, pagination) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
return;
} else {
for (var i = 0; i < results.length; i++) {
var markerPlace = results[i];
createMarkers(markerPlace, status);
}
if (pagination.hasNextPage) {
var moreButton = document.getElementById('more');
moreButton.disabled = false;
google.maps.event.addDomListenerOnce(moreButton, 'click',
function () {
moreButton.disabled = true;
pagination.nextPage();
});
}
}
}
function createMarkers(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var bounds = new google.maps.LatLngBounds();
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
placesList.innerHTML += '<li>' + place.name + '<br>' +
(place.formatted_address ? place.formatted_address : place.vicinity) + '</li>';
bounds.extend(place.geometry.location);
map.fitBounds(bounds);
}
}
});
google.maps.event.addDomListener(window, 'load', initialize);
Your address is not a string, it is a number:
var address = 14235;
The API expects the "address" in the GeocoderRequest to be a string that looks like a postal address. If you want it to be a string, enclose it in quotes (although I'm not sure what you expect the geocoder to return for a single number):
var address = "14235";
If you give the geocoder something that looks more like a complete address, it will work better.
You also have a problem with the asynchronous nature of the geocoder (a FAQ), you can't return the result of an asynchronous function, you need to use it in the callback function.
What you have to understand is that the geocode API is asynchronous; you're trying to assign the results variable to pyrmont before it's ready. To achieve what you want you're going to need to use a callback. Plus there's some other things wrong with how you're dealing with latLng attributions. Anyway, here's how I think your code should look:
var map, geocoder; // global vars
// retain your initialize function
function initialize() {
map = new google.maps.Map(document.getElementById('map'), options);
geocoder = new google.maps.Geocoder();
}
// but separate out your code into a new function that accepts an address
// and a callback function.
function getLatLng(address, callback) {
geocoder.geocode({ address: address }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
// assign a new Google latLng object to `location`
var location = new google.maps.LatLng(result.lat(), result.lng();
// set the center of the map and position using the latlng object
map.setCenter(location);
var marker = new google.maps.Marker({
map: map,
position: location;
});
// call the callback with the latlng object as a parameter.
callback(location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
// call the `getLatLng` function with an address and a callback function
getLatLng('14235', function (latLngLocation) {
var pyrmont = latLngLocation;
});
Hey everybody! Im trying to use getLatLng() to geocode a list of postal/zip codes and store the generated point in the database to be placed on a map later. This is what I've got so far:
$(".geocodethis").click(function () {
var geocoder = new GClientGeocoder();
var postalCode = $(this).siblings(".postal").val();
var id = $(this).siblings(".id").val();
geocoder.getLatLng(postalCode, function (point) {
if (!point) {
alert(postalCode + " not found");
} else {
alert(point);
var serializedPoint = $.param(point);
//Geocode(id, point);
}
});
});
function Geocode(id, point) {
alert(point);
$.post("/Demographic/Geocode/" + id, point, function () {
alert("success?");
});
}
but I'm getting this.lat is not a function in my error console when i try to serialize the point object or use it in $.post()
From my research, I understand that geocoder.getLatLng() is asynchronous, how would that affect what I'm trying to do? I'm not running this code in a loop, and I'm trying to post the point using the anonymous callback function.
How can I save the information from point to use later?
Update
Creating a marker and trying to post that still results in the this.lat is not a function in the error console.
$(".geocodethis").click(function () {
var geocoder = new GClientGeocoder();
var postalCode = $(this).siblings(".postal").val();
var id = $(this).siblings(".id").val();
geocoder.getLatLng(postalCode, function (point) {
if (!point) {
alert(postalCode + " not found");
} else {
alert(point);
var marker = new GMarker(point);
$.post("/Demographic/Geocode/" + id, marker, function () {
alert("success?");
});
}
});
});
** Another Update **
I really need to save the geocoded address for later, even if I store the latitude/longitude values in my database and remake the marker when I'm ready to put it onto a map. Again, serializing or posting - seemingly using the point in any way other than in google maps functions gives the this.lat is not a function exception in my error log.
I'm using asp.net mvc - are there any frameworks out there that would make this easier? I really need help with this. Thanks.
If your stuck for 2 days maybe a fresh v3 start would be a good thing, this snipped does a similair job for me...
function GetLocation(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
ParseLocation(results[0].geometry.location);
}
else
alert('error: ' + status);
});
}
}
function ParseLocation(location) {
var lat = location.lat().toString().substr(0, 12);
var lng = location.lng().toString().substr(0, 12);
//use $.get to save the lat lng in the database
$.get('MatchLatLang.ashx?action=setlatlong&lat=' + lat + '&lng=' + lng,
function (data) {
// fill textboss (feedback purposes only)
//with the found and saved lat lng values
$('#tbxlat').val(lat);
$('#tbxlng').val(lng);
$('#spnstatus').text(data);
});
}
Have you tried this?
$(".geocodethis").click(function () {
var geocoder = new GClientGeocoder();
var postalCode = $(this).siblings(".postal").val();
var id = $(this).siblings(".id").val();
geocoder.getLatLng(postalCode, function (point) {
if (!point) {
alert(postalCode + " not found");
} else {
alert(point);
var marker = new GMarker(point);
map.addOverlay(marker);
obj = {lat: marker.position.lat(),
lng: marker.position.lng()};
$.post("/Demographic/Geocode/" + id, obj, function () {
alert("success?");
});
}
});
});
I haven't used V2 in a long time, so I'm not sure about the exact syntax, but the point is to create an object from the information you need (lat/lng) and serialize that.
Also, an upgrade to V3 is much recommended, if plausible.
You need to set a marker on the map, which takes a lat/long. You can save that info however you want or display immediately. (Code truncated for demo purpose)
map = new google.maps.Map(document.getElementById("Map"), myOptions);
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location
});
marker.setMap(map);
}
}
UPDATE (FOR v2)
$(".geocodethis").click(function () {
var geocoder = new GClientGeocoder();
var postalCode = $(this).siblings(".postal").val();
var id = $(this).siblings(".id").val();
geocoder.getLatLng(postalCode, function (point) {
if (!point) {
alert(postalCode + " not found");
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
}
});
});
In V3 the coordinates must be first serialized as a string as shown by Arnoldiuss, before sending as json post data.
var lat = latlong.lat().toString().substr(0, 12);
var lng = latlong.lng().toString().substr(0, 12);
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<%# taglib prefix="s" uri="/struts-tags"%>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyDS1d1116agOa2pD9gpCuvRDgqMcCYcNa8&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var latitude = document.getElementById("latitude").value;
latitude = latitude.split(",");
var longitude = document.getElementById("longitude").value;
longitude = longitude.split(",");
var locName = document.getElementById("locName").value;
locName = locName.split(",");
var RoadPathCoordinates = new Array();
RoadPathCoordinates.length = locName.length;
var locations = new Array();
locations.length = locName.length;
var infowindow = new google.maps.InfoWindow();
var marker, i;
var myLatLng = new google.maps.LatLng(22.727622,75.895719);
var mapOptions = {
zoom : 16,
center : myLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//To Draw a line
for (i = 0; i < RoadPathCoordinates.length; i++)
RoadPathCoordinates[i] = new google.maps.LatLng(latitude[i],longitude[i]);
var RoadPath = new google.maps.Polyline({
path : RoadPathCoordinates,
strokeColor : "#FF0000",
strokeOpacity : 1.0,
strokeWeight : 2
});
//Adding Marker to given points
for (i = 0; i < locations.length; i++)
locations[i] = [locName[i],latitude[i],longitude[i],i+1];
for (i = 0; i < locations.length; i++)
{marker = new google.maps.Marker({
position : new google.maps.LatLng(locations[i][1], locations[i][2]),
map : map
});
//Adding click event to show Popup Menu
var LocAddress ="";
google.maps.event.addListener(marker, 'click', (function(marker, i)
{ return function()
{
GetAddresss(i);
//infowindow.setContent(locations[i][0]);
infowindow.setContent(LocAddress);
infowindow.open(map, marker);
}
})(marker, i));}
function GetAddresss(MarkerPos){
var geocoder = null;
var latlng;
latlng = new google.maps.LatLng(latitude[MarkerPos],longitude[MarkerPos]);
LocAddress = "91, BAIKUNTHDHAAM"; //Intializing just to test
//geocoder = new GClientGeocoder(); //not working
geocoder = new google.maps.Geocoder();
geocoder.getLocations(latlng,function ()
{
alert(LocAddress);
if (!response || response.Status.code != 200) {
alert("Status Code:" + response.Status.code);
} else
{
place = response.Placemark[0];
LocAddress = place.address;
}
});
}
//Setting up path
RoadPath.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<s:form action="mapCls" namespace="/">
<s:hidden key="latitude" id="latitude"/>
<s:hidden key="longitude" id="longitude"/>
<s:hidden key="locName" id="locName"/>
<div id="map_canvas" style="float:left;width:70%;height:100%"></div>
</s:form>
</body>
</html>
I am doing reverse Geocoding, and want address of marker using lat and longitude. M facing problem with function "GetAddresss()", line "geocoder.getLocations(latlng,function ()" is not working properly. what should I Do?