Convert lat,lng into Address and show on infoWindow google map api - google-maps

I have list of lat, lng values in object
var path = [{"lat":"12.9247903824","lng":"77.5806503296"},{"lat":"10.9974470139","lng":"76.9459457397"}]
Here i have to convert latlng into address and have to show marker and infowindow. Address have to be shown in info window
I have tried this one, i have getting address and multiple markers but i not able to show address on info windows.. last infowindow only showing address
for (var i = 0; i < path.length; i++) {
var pos = new google.maps.LatLng(path[i]["lat"], path[i]["lng"]);
var marker = new google.maps.Marker({
position: pos,
map: map
});
geocoder.geocode({'latLng': pos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
infowindow.setContent(results[i].formatted_address);
} else {
alert('Geocoder failed due to: ' + status);
}
});
}

Do you have a listener to open the infowindow when you click a marker? Insert the geocoder function inside that listener, do the geocode, set content to the infowindow and then open the infowindow.

Related

Could not centralise the google map after location search in angular 2

I have a input field and a button. On click of button the location whatever written in the input field will set a marker in google map. I am able to locate a marker in map. But it wont appear in the centre. In fact map will stay constant whatever the location you search.
getAddress(place:Object) {
this.markers = [];
var address = this.step1Data.map_address;
if (!address) return false;
var geocoder = new google.maps.Geocoder();
var that = this;
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
var lat = location.lat();
var lng = location.lng();
that.markers.push({
lat: lat,
lng: lng,
label: 'A',
draggable: false
})
that._googleMapsApi.setCenter(location);
}
});
}
setCenter() method is not working here. May I know the reason. googleMapsApi is imported from angular2-google-maps/core.

Geocode to produce multiple markers google maps

Can any suggest why this code doesn't provide 2 markers on my map?
http://pastebin.com/1uaNjeVy
I'm not sure whether it is a syntax error or a restriction by google?
Edit:
I got it working by doing the below anyway, apologies for not posting the code direct to here.
My new issue is that when I open the page sometimes it finds all of the addresses, other times it brings up the alert?
var geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': "Eldon Square 24-26 Sidgate, Newcastle upon Tyne"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var img = "https://dl.dropboxusercontent.com/u/55888592/marker26.png";
var info = "<div><p>Sometext</p></div>";
var infowindow = new google.maps.InfoWindow({
});
var latlng = results[0].geometry.location;
var marker = new google.maps.Marker({
icon: img,
position: latlng,
map: map,
content: info
});
google.maps.event.addListener(marker, "click", function(content) {
infowindow.setContent(this.content);
infowindow.open(map,this);
});
} else {alert("alert");
}
marker.setMap(map);
});
The geocoder is asynchronous. Your are setting the marker map variable before the marker is created. You should do that in the callback function of the geocoder. (The javascript console is your friend)
And your marker images fail to load from the URL provided (probably because it is https)
working example

Google Maps v3, reverse Geocoding and multiple Infowindow

I'm working on a google map v3.
On this map I want display several markers each one with its Infowindow where shows some information about that point.
The source of information is an javascript array with some data for each point, and up here everything works fine.
The array contains (SOMETIMES) the address (sometimes null) and ALWAYS lat-long coordinates, so when the address isn't present I have to make a reverse-geocoding. Here my code:
var geocoder = new google.maps.Geocoder();
for(var i=0;i<markersArray.length;i++){
var la=markersArray[i][0]);
var lo=markersArray[i][1]);
gpoint=new google.maps.LatLng( la,lo);
var aMarker = new MarkerWithLabel({ //part of Google Maps Utility Lib
position: gpoint,
map: map,
labelContent: deviceID,
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labelStyle",
html: "<ul><li>Speed: "+markersArray[i][3]+"</li></ul>",
address: markersArray[i][4]
});
if (aMarker.address<="" || aMarker.address==null) {
geocoder.geocode({'latLng': gpoint}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
aMarker.address=results[1].formatted_address;
}
}
});
}
google.maps.event.addListener(aMarker, 'click', function () {
infowindow.setContent(this.html+" "+this.address);
infowindow.open(map, this);
});
....
}
Almost everything is ok: the markers are in position and all them show the right infowindow with the right addresses except those where the addresses were empty and were reverse-geocoding.
For this last set only the last one marker infowindow shows the right address, all other infowindow addresses's are empty.
Any idea?
Very thanks!
One way to fix this is to create a function which does the reverse geocoding and can have function closure on the infowindow and the marker.
As the reverse geocode operation is asynchronous, the returned address isn't available for any except the last marker.

Geocoding using Google Maps API v3 - Linking the original request to the response

I have a list of schools that I want to plot on a Google Map. I'm using Google's Geocoding Service to lookup the lng/lat for a given postcode, upon successfully retrieving this information I want to drop a marker, together with adding the appropriate event listener that opens an infobox when a given marker is clicked.
When I make a request to the geocoder it's in the context of a school, when I receive a callback I lose this context. You'll see from code below that I've come up with a clunky solution to this, although it fails occasionally when the geocoder results truncate the postcode.
Should I be using something like jQuery's Deferred Object to solve this issue?
var geocoder;
var map;
var infowindow
var iterator = 0;
geosearch = new Array();
function drop() {
for (var i = 0; i < schools.length; i++) {
setTimeout(function() { // delay added to prevent being throttled
addMarker();
iterator++;
}, i * 1000);
}
}
function addMarker() {
address = schools[iterator].addresses[0].address.zip;
geosearch[address] = schools[iterator]; // this is how I'm keeping track of initial request
geocoder.geocode( { 'address': address }, function(results, status) {
var school = geosearch[results[0].address_components[0].short_name]; // loading the school associated with the initial request, which only works if the postcode completely matches up - clunky!
if (status == google.maps.GeocoderStatus.OK) {
// each school has tags, I want to set a marker if certain tags exist
if ($.inArray('D', school.tags) > 0) {
var image = 'map_markers/brown_MarkerD.png';
} else if ($.inArray('C', school.tags) > 0) {
var image = 'map_markers/red_MarkerC.png';
} else if ($.inArray('B', school.tags) > 0) {
var image = 'map_markers/yellow_MarkerB.png';
} else if ($.inArray('A', school.tags) > 0) {
var image = 'map_markers/green_MarkerA.png';
} else {
var image = 'map_markers/blue_MarkerZ.png';
}
// add the marker to the map, using result
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
draggable: false,
icon: image,
shadow: 'http://www.google.com/mapfiles/arrowshadow.png',
animation: google.maps.Animation.DROP
});
// adds listening on marker so that popup box appears when clicked
google.maps.event.addListener(marker, 'click', (function(marker, school) {
return function() {
infowindow.setContent(
''+school.name+''
+'<address>'
+school.addresses[0].address.street+'<br />'
+school.addresses[0].address.city+'<br />'
+school.addresses[0].address.state+'<br />'
+school.addresses[0].address.zip+'<br />'
+school.addresses[0].address.country+'<br />'
+'</address>');
infowindow.open(map, marker);
}
})(marker, school));
} else {
console.log("* NOT found: " + status);
}
});
}
function initialise() {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(54.82659788452641,-3.417279296874991);
var mapOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
drop(); // loops through schools to add marker
}
I would suggest geocoding the addresses offline and storing the coordinates in your database (or wherever you are storing the addresses). Then use the coordinates to display the markers.
I would also suggest reviewing this article on geocoding strategies from the documentation
To answer your question, I would suggest using javascript function closures to associate the address with the callback function.
The problem I was experiencing here was just a questions of scope, and in particular the way that I was referencing the school within the addMarker() function. Rather than referencing the school within the schools array using the global iterator variable, I instead pass in this school, this way the correct school is always referenced on the callback that is created within this scope.
var geocoder;
var map;
var infowindow
var iterator = 0;
function drop() {
for (var i = 0; i < schools.length; i++) {
setTimeout(function() {
addMarker(schools[iterator]); // pass in the school as an argument
iterator++;
$('#current_school').text(iterator); // taken this out of addMarker()
}, i * 1000);
}
}
function addMarker(school) {
geocoder.geocode( { 'address': school.addresses[0].address.zip }, function(results, status) {
... // the inners from here remain the same
});
}

Display multiple markers on google map by providing address

I have the following script to use the google maps API, I have to create a map that has more than one Marker (the balloon shaped icon pointing to something) and i need each of those markers to point on a different area of the map (i.e. different coordinates), how can i do it?
NOTE: I do not have latitude and longitude for the area on which marker has to be placed instead I have the address of the area on which marker has to be placed.
The code to display multiple markers on Google map is given below but it does not work as expected!
var map = null;
var geocoder = null;
function initializeNew() {
var allAddress = document.getElementById("HiddenField1").value;
var testary = new Array();
testary = allAddress.split("|");
if (GBrowserIsCompatible()) {
//calls map to appear inside <div> with id, "map_canvas"
map = new GMap2(document.getElementById("map_canvas"));
//adds zoom and arrow controls to map
//map.addControl(new GSmallMapControl());
var marker = null;
var i = 0;
for (i = 0; i < testary.length; i++) {
address = testary[i];
geocoder = new GClientGeocoder();
//converts a street address into geocode for the api
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 13);
marker = new GMarker(point);
map.addOverlay(marker);
map.setMapType(G_HYBRID_MAP);
//adds your own marker title and description in html
marker.openInfoWindowHtml("<p class='para1bold' style=\"font-weight: bold;\">Address</p><p class='para1'>" + address + "</p>");
//Add click event on push pin to open info window on click of the icon
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("<p class='para1bold' style=\"font-weight: bold;\">Address</p><p class='para1'>" + address + "</p>");
});
//Provides map,satellite,hybrid and terrain views in the map along with zoom control
map.setUIToDefault();
}
}
)
}
}
}
I have stored address of group of items in an array and looped to display markers in the map. This displays only one marker for the last address present in the array. Please correct this code or provide new code to display multiple markers in Google map by providing address.
I ran into this exact same problem and fixed it. Look at the code that I have used. The specific bits are that marker needs to be an array and when you open the infowindow the content needs to be stored in the marker array. I would also suggest that you use something JSON instead which is easier to parse instead of separating with '|'.
try this: put var in front of marker
else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
map.setMapType(G_HYBRID_MAP);
//adds your own marker title and description in html
marker.openInfoWindowHtml("<p class='para1bold' style=\"font-weight: bold;\">Address</p><p class='para1'>" + address + "</p>");
//Add click event on push pin to open info window on click of the icon
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("<p class='para1bold' style=\"font-weight: bold;\">Address</p><p class='para1'>" + address + "</p>");
});
UPDATE
var geocoder = new GClientGeocoder();
var addresses = ["new york","chicago"];
var curIndex = 0;
function showAddress() {
var _cur = addresses[curIndex];
geocoder.getLatLng(
_cur,
function(point) {
if (!point) {
alert(_cur + " not found");
} else {
console.log(_cur+":"+point);
}
//do next after done
curIndex++;
if(curIndex<addresses.length)
showAddress();
}
);
}
showAddress();
</script>