Google Maps v3, reverse Geocoding and multiple Infowindow - google-maps

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.

Related

need to add multiple markers using custom google map api

i was checking out the google map api to integrate in my website.
made this page with what ever i could understand so far.
everything is working fine but there is just one thing, that i want three markers on the same map.
when i am adding more than one markers then the map stops working.
test link : http://goo.gl/X9q92s
you will have a better understanding if u see my link.
this is the code that i got from google map api.
and i edited it to get grey scale map with my desired marker box.
i just want to add two more....
Please help.
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You should place your "new marker" code into its own function, like so:
function LoadMarkers(name, lat, lng) {
var MarkerLatLng = new google.maps.LatLng(lat, lng);
var MarkerOption = { map: map, position: MarkerLatLng, title: name};
var Marker = new google.maps.Marker(MarkerOption);
}
Putting this into its own function allows you to "refresh" the markers with ease, by simply invoking the function with a timer or some other event. A program I'm working on refreshes the map every few seconds, as my data source is constantly changing with new/removed/updated records that should be reflected immediately on the map. I think this is a great way to do this.
Then, in your program, you can create a loop that shoots the information for each marker in by invoking the LoadMarkers function. I've recently fallen in love with SqlDataReader.
Your loop would iterate through a SqlDataReader and each record read will invoke the script like so:
InvokeScript("LoadMarkers", New Object() {name, lat, lng})
This is a great moment to also add an InfoWindow for each marker.
var infowindow = new google.maps.InfoWindow(
{
content: "Content here"
});
As well as a click listener for the InfoWindows. ;)
google.maps.event.addListener(Marker, 'click', function () {
typeof infoWindowsOpenCurrently !== 'undefined' && infoWindowsOpenCurrently.close(); //If there is an InfoWindow currently open, close it
infowindow.open(map, Marker); //Open a new one for the selected marker
infoWindowsOpenCurrently = infowindow; //Set the new info window to the temporary variable
});
Some might not like this method of using a loop. I like it because I can "personalize" each marker for each record, while personalizing each of their InfoWindows too. In my code above, assume that "name" is a unique ID that lets you specify a specific marker for later use, such as identifying which marker was clicked and which InfoWindow is currently open.

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 API - Radius search for markers using Places?

I have set up a Google Map using API v3. The map has a number of markers with infoboxes attached. I am looking to set up a search box outside of the map for the user to input an address and then have the nearest markers returned based on the distance away (such as a radius search).
From the API documentation I think I need to uses the Places services. Can anyone point me in the right direction?
To do a radius search with the API, use the Geometry Library google.maps.geometry.spherical.computeDistanceBetween method to calculate the distance between each marker and the geocoded result from the address. If that distance is less than the requested radius, show the marker, else hide it.
code assumes:
array of google.maps.Markers called gmarkers
google.maps.Map object called map
function codeAddress() {
var address = document.getElementById('address').value;
var radius = parseInt(document.getElementById('radius').value, 10)*1000;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
if (circle) circle.setMap(null);
circle = new google.maps.Circle({center:marker.getPosition(),
radius: radius,
fillOpacity: 0.35,
fillColor: "#FF0000",
map: map});
var bounds = new google.maps.LatLngBounds();
for (var i=0; i<gmarkers.length;i++) {
if (google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),marker.getPosition()) < radius) {
bounds.extend(gmarkers[i].getPosition())
gmarkers[i].setMap(map);
} else {
gmarkers[i].setMap(null);
}
}
map.fitBounds(bounds);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
example

Mini Map in InfowWindow for direction route

I am working in Google Map v3(actually migrating V2 to V3), and trying to customize the Infowindow of the Direction Service.
I am able to display the Direction using Origin, Destination and waypoints.
My Map displayed the route correctly with Marker (green marker with A, B, C... text).
By default, On click of teh marker infowindow will display address of that marker.
I want to customize it, so that on click of marker it should disply mini map of that location in Infowindow with more zoom.
I am able to do some progress, but the problem here is,
- Marker is changed to red pointing marker instead of Green marker (with A, B, C...text)
- whichever the marker I click, infowindow will open on the last marker
- Once marker is clicked it will display minimap, but on close and again click of that marker it will display address (default behaviour)
- my code is actually overwriting the green marker with red pointed marker
Can soboby help me how to fix all these issue
Below is my code:
function CreateDirection (arrWaypoints) {
if (!this.directions) {
this.directions = new google.maps.DirectionsService();
var origin = arrWaypoints[0];
var destination = arrWaypoints[arrWaypoints.length - 1];
var tripWaypoints = [];
for (var i = 1; i < arrWaypoints.length - 1; i++) {
tripWaypoints.push({
location: new google.maps.LatLng(arrWaypoints[i].hb, arrWaypoints[i].ib),
stopover: true
});
}
var myMap = MyMap.getMap();
var steps = [];
this.directions.route({
origin: origin,
destination: destination,
waypoints: tripWaypoints,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.DirectionsUnitSystem.METRIC
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay = new google.maps.DirectionsRenderer();
// directionDiv div element in my page
directionsDisplay.setPanel(document.getElementById("directionDiv"));
directionsDisplay.setMap(myMap);
directionsDisplay.setDirections(result);
}
});
}
}
function CreateMiniMapInfoWindow (wayPointsArray) {
for (var i = 0; i < wayPointsArray.length; i++) {
var myMap = MyMap.getMap();
var marker = new google.maps.Marker({
position: wayPointsArray[i],
map: myMap
});
google.maps.event.addListener(marker, 'click', function() {
var myOptionsMini = {
zoom: 14,
center: wayPointsArray[i],
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var infowindow = new google.maps.InfoWindow();
var minimap = new google.maps.Map(document.getElementById ("minimap"), myOptionsMini);
document.getElementById("minimap").style.display = 'block';
minimap.setCenter(marker.getPosition());
var minimapDiv = document.getElementById("minimap");
infowindow.setContent(minimapDiv);
infowindow.open(myMap, marker);
});
}
}
I need the solution for:
- How to get customized infowindow (with minimap) for all the markers
- How to put the green markers with text A, B, C...
Attached image is what I am getting from the above code
I hope my question is clear.
Please let me know if anyone have any inputs.
Thanks,
Sharath
Pass the following object as argument to the DirectionsRenderer:
{markerOptions:{clickable:false,zIndex:1000}}
It will have 2 effects:
the custom markers will be placed behind the A,B,C-markers created by the DirectionsRenderer(currently they are still present, but behind your custom markers)
the markers created by the DirectionsRenderer are not clickable, the underlying custom markers are able to receive the click.
another option(I would prefer it): set the suppressMarkers-option of the DirectionsRenderer to true and use the A,B,C-markers for your custom markers(e.g. https://maps.gstatic.com/mapfiles/markers2/marker_greenA.png , https://maps.gstatic.com/mapfiles/markers2/marker_greenB.png )
Related to the infoWindow: all you need is 1 infoWindow with 1 map for all markers. Observe the click-event of the markers and when it occurs open the infoWindow and center the map inside the infowindow at the markers position(may be retrieved inside the click-callback via this.getPosition())
Note: instead of using your predefined waypoints you better parse the route returned by the directionsService to place the custom markers at the exact positions(these may differ from your predefined waypoints)

google geocoder service

I'm trying to use Google geocoder service to get the coordinates of cities input by the user. However looks like there's some problem initializing the LatLng() object (latlngCity), and the map won't show up. The code is as following:
var map;
var latlngCity;
function initialize() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': 'Lisbon, PT'}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
latlngCity = results[0].geometry.location;
}
});
var myMapOptions = {
zoom: 8,
center: latlngCity,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myMapOptions);
}
For simplicity, I'm inserting the address city string myself. Variables map and latlngCity are globals. Is there anything wrong with this code?
Thanks very much.
You need to move the map creation code into the geocode callback (or alternatively create the map with some default position and then re-center the map inside the callback).
In your code, latlngCity is undefined by the time of map creation while geocode is still being executed (asynchronously).
Hope this makes sense. Otherwise I'll provide some code. Let me know.