Saving Dragable Directions Google Directions API v3 - javascript

I'm making an app with the Directions API to create biking directions. The user needs to be able to start from a custom point, add custom stopping points along the route, and actually drag the directions. Once they're done, I need to save the new route to a database.
I have the map up and running, users can add their start and waypoints via HTML input boxes, and it's perfectly dragable (sorry for the copious amounts of comments…those are primarily so I can remember what's going on…oh, and don't worry in this section about syntax…I'm copying and pasting from different parts, so I might have missed a "}"…all of this code functions):
function initialize() {
var rendererOptions = {
draggable: true,
//end redererOptions
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var chicago = new google.maps.LatLng(42.73352,-84.48383);
var myOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago,
//end myOptions
}
//create the world of the dream (define where the map's gonna go
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//and the subject fills it with it's subconscious (Call the map from Directions and place it in the div we've created)
directionsDisplay.setMap(map);
//tell google where the printed directions will go
directionsDisplay.setPanel(document.getElementById("directions_detail"));
//end initialize()
};
function calcRoute() {
//get start string from Start input box
var start = document.getElementById("start").value;
//get end string from End input box
var end = document.getElementById("end").value;
//set up an array for waypoints
var waypts = [];
//define where the waypoints will come from
var checkboxArray = document.getElementById("waypoints");
//loop to retrieve any waypoints from that box
for (var i = 0; i < checkboxArray.length; i++) {
//if any options in the select box are selected, add them
if (checkboxArray.options[i].selected == true) {
waypts.push({
//set up parameters to push to the Directions API
location:checkboxArray[i].value,
//make them explicit waypoints that separate the route into legs
stopover:true});
//end if loop
}
//call the Directions Service API, pass the request variable (above) and call a function asking for the response and status objects
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK)
{
//pass the response object to the map
directionsDisplay.setDirections(response);
//set up a route variable for the upcoming loop
var route = response.routes[0];
//set up a variable for the route summary, define the <div> where this will be presented to the user
var summaryPanel = document.getElementById("directions_panel");
//clear the <div>
summaryPanel.innerHTML = "";
//turn direcitons_panel "on"...gives the div a color (in my css)
summaryPanel.className = "directions_panel_on";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
//set up a route segment variable to display a 1-based segment for the segment summary in html
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
//end for loop
};
//end directionsService() function
});
//end calcRoute() function
}
SO. You have my base. Everything's functional (I have it running on my server)…users can create a fully customized map. I just can't save it if they decided to drag the path of the route because I need to call an object with AJAX, and the only object I know how to call is tied to the request variable, which defines the waypoints array as the hard stopover points that split the route up.
I know that the array I'm looking for is called via_waypoint[]inside of the legs[] array…it's just getting an object out of the damn DirectionsRenderer with the stupid via_waypoints[] array populated. I have the rest ready to go on the PHP/MySqul and AJAX side of things.
I've already tried this tutorial…and I can't get it to work. The main answer itself says it left out a lot, and I'm so new to JavaScript, it appears (s)he left out too much for me.

I was trying for saving waypoints and this should be useful to other users who are searching for the same.
I have created set of scripts to save the directions waypoints in the database also code to fetch that information back and display the waypoints in another map. I have provided html, php and sql files and complete explanation in this link.
http://vikku.info/programming/google-maps-v3/draggable-directions/saving-draggable-directions-saving-waypoints-google-directions-google-maps-v3.htm.
Also you can copy the source code of that page and you can edit according to your preference and use the sql file for the database.

UPDATE: I've found my own answer.
The object that houses the most current map data is directionsDisplay.directions. That object holds the data from the map AS SHOWN…including the via_waypoints[] array, which shows up as a child of the legs[] array.
The code below shows how you can print the string for your analyzing pleasure (I've made this function to be called by a button on the HTML side):
//GET THE JSON Object
var newString = JSON.stringify(directionsDisplay.directions);
//set up area to place drop directionsResponse object string
var directions_response_panel = document.getElementById("directions_response");
//dump any contents in directions_response_panel
directions_response_panel.innerHTML = "";
//add JSON string to it
directions_response_panel.innerHTML = "<pre>" + newString + "</pre>";
Lesson of the night: directionsDisplay.directions calls on the map data AFTER a user has made dragable changes to their directions.

Related

leaflet getBounds() errors

I am trying to getBounds of dynamically added markers to the map. My goal is to dynamically add markers to a map and have the view automatically zoom to fit the bounds of all the markers on the map. Below is my current code and what I have tried so far:
The starting point is an array of lat & lng:
The web page offers a list of addresses and checkboxes that a user can select and deselect. When the desired addresses are selected the user can click view on map and the makrers will appear on the map (this is working perfectly, I just can't get the view to zoom to the bounds of these markers)
I have a loop that pulls the lat and lng for each checked address and pushes it into an array like this:
latLng.push(42.9570316,-86.04564429999999);
latLng.push(43.009381,-85.890041);
...this is in a loop so it always contains the desired amount of values and outputs this:
latLng = [42.9570316,-86.04564429999999,43.009381,-85.890041,43.11996200000001,-85.42854699999998,43.153376,-85.4730639,42.8976947,-85.88893200000001];
var thisLatLng = L.latLng(latLng);
console.log(thisLatLng); // this returns Null
mymap.fitBounds(group); // returns Error: Bounds are not Valid
mymap.fitBounds(group.getBounds()); // returns group.getBounds() is not a function
I have also tried this as a starting point:
latlng.push(L.marker([42.9570316,-86.04564429999999]));
latlng.push(L.marker([43.009381,-85.890041]));
...this is contained in a loop that results in the output below
latLng = [L.marker([42.9570316,-86.04564429999999]),L.marker([43.009381,-85.890041]),L.marker([43.11996200000001,-85.42854699999998]),L.marker([43.153376,-85.4730639]),L.marker([42.8976947,-85.88893200000001])];
console.log(latLng); // this returns makrers with the correct lat & lng above
var group = new L.featureGroup(latLng);
console.log(group); //this returns a Null featureGroup
mymap.fitBounds(group); // returns Error: Bounds are not valid
mymap.fitBounds(group.getBounds()); // returns Error: Bounds are not valid
I am at a loss on how to make this work I have tried several answers posted on stackoverflow and attempted to try and follow the documentation but nothing seems to give the desired outcome.
Update
I removed latLng.push(L.marker([42.9570316,-86.04564429999999])); loop and replaced with the following:
I created a featuregroup with var group = new L.featureGroup(); then added markers to it in the loop by using marker.addTo(group); this pushed all of the markers into the featuregroup as I would expect but was unable to get bounds.
mymap.fitBounds(group.getBounds()); // returns Error: Bounds are not valid
here is what console.log(group); outputs:
I don't think at all that
latLng = [L.marker([42.9570316,-86.04564429999999]),L.marker([43.009381,-85.890041]),L.marker([43.11996200000001,-85.42854699999998]),L.marker([43.153376,-85.4730639]),L.marker([42.8976947,-85.88893200000001])];
Can work. In leaflet you can't just create a variable and say that it's a marker object. You need to use method like L.marker()
What you need to do is create a single marker and add it to a featureGroup
var group = new L.featureGroup();
for (var i = 0; i < yourMarkers.length; i++) {
L.marker([51.5, -0.09]).addTo(group);
}
map.fitBounds(group.getBounds());
group will now contains multiple markers.
And you can also try this :
var coordinates = new Array();
for (var i = 0; i < yourMarkers.length; i++) {
var marker = L.marker([51.5, -0.09]);
coordinates.push(marker);
}
var group = new L.featureGroup(coordinates);
map.fitBounds(group.getBounds());
UPDATE
The concerned function was this one :
function showResult(lat, lng) {
var marker = L.marker([lat, lng])
.bindPopup('yourPopup').on("popupopen", onPopupOpen).addTo(group);
map.addLayer(group);
map.fitBounds(group.getBounds());
}
You only need to add the fitBounds() inside it.

Google Maps Api getting the title from the marker

When I push a marker to the array it plots the marker correctly and adds a title to the array too.
I know this works because when I console.log the console.log(markersArray); it returns the following. the title of the marker is next door.
The below is my marker click that opens up the info window, but when I console.log out the data which is called mll it doesn't have the title inside it.
google.maps.event.addListener(marker, 'click', function(mll) {
console.log(mll);
var html= "<div style='color:#000;background-color:#fff;padding:5px;width:150px;'><p>"+mll+"</p></div>";
iw = new google.maps.InfoWindow({content:html});
iw.open(map,marker);
});
How would I be able to get the click function to pull in the title when the array has it and has pushed it successfully?
I remember doing something similar before. In my case, I used infoWindows with circle markers. Essentially, I had both in separate arrays. When I made the circle marker, I gave it a unique value, called place, which was basically it's count (the value of the n-th circle created, was n). On the event listener, I called the infoWindow from the other array based on the position of the current circle.
You can make an array var titles = []; to hold titles.
Each time you make a new marker, increment a var count = 0;, keeping track of how many markers you have.
In your marker options, add place: count. When you need a specific title, you can call titles[marker.place];
var infos = [];
var count = 0;
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var lastWindow;
count++;
var populationOptions = {
//leaving out defaults
place: count
};
var circle = new google.maps.Circle(populationOptions);
lastCircle = circle;
var contentString = 'just a string...';
var infowindow = new google.maps.InfoWindow({
content: contentString,
position: new google.maps.LatLng(data.lon, data.lad)
});
infos.push(infowindow);
google.maps.event.addListener(circle, 'mouseover', function() {
if(lastWindow){
lastWindow.close();
}
infos[circle.place].open(map);
lastWindow = infos[circle.place];
});

Google Maps (in .net) - Drawing another map on top of existing?

I've got a 3 pane google map integration in our VB.net software. For the most part it works brilliantly. Today I'm trying to get these 3 seperate objects to paint different polygons depending on the lat/lngs they're sent for each day.
First map control works all of the time. 2nd and 3rd however are being troublesome. I've attempted to screenshot what's going on.
As you can see, the polys are being drawn, but for some reason an entirely new map is being drawn on top of my original. Obviously this isn't right. I've got code all over the place too:
Here's the JS initialize that is called upon DocumentComplete firing:
function Initialize(zoomLevel,lat,lng,type, bCanEdit, bCanDrag){
//Get the type of map to start.
//Need to convert the GoogleMapType enum
//to an actual Google Map Type
var MapType;
switch (type)
{
case 1:
MapType = google.maps.MapTypeId.ROADMAP;
break;
case 2:
MapType = google.maps.MapTypeId.TERRAIN;
break;
case 3:
MapType = google.maps.MapTypeId.HYBRID;
break;
case 4:
MapType = google.maps.MapTypeId.SATELLITE;
break;
default:
MapType = google.maps.MapTypeId.ROADMAP;
};
//Create an instance of the map with the lat, lng, zoom, and
//type passed in
myLatlng = new google.maps.LatLng(lat,lng);
var myOptions = {zoom: zoomLevel,center: myLatlng,mapTypeId: MapType};
var MarkerSize = new google.maps.Size(48,48);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', Map_Click);
google.maps.event.addListener(map, 'mousemove', Map_MouseMove);
google.maps.event.addListener(map, 'idle',Map_Idle);
overlayLayer = new Array();
overlayCount = 0;
driverRouteLayers = new Array();
driverRouteCount = 0;
canEdit = bCanEdit;
canDrag = bCanDrag;
}
The VB.net that invokes the script to draw the overlay areas:
Public Sub DrawAreaOverlays(ByVal area As DeliveryArea)
Dim gc As New GComArray()
For Each p As DeliveryAreaPoint In area.Points
Dim ll As New GLatLong(p.Latitude, p.Longitude)
gc.Add(ll)
Next
WebBrowser1.Document.InvokeScript("DrawAreaOverlay", {gc, Utility.Pens.GetHexColor(area.Colour)})
End Sub
And the initial DocumentComplete hook-in in vb.net:
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
'Initialize the google map with the initial settings.
'The Initialize script function takes four parameters.
'zoom, lat, lng, maptype. Call the script passing the
'parameters in.
WebBrowser1.Document.InvokeScript("Initialize", New Object() {InitialZoom, InitialLatitude, InitialLongitude, CInt(InitialMapType),
allowEditing, allowDragging})
RaiseEvent PopulateInitialRoutes()
End Sub
These are the only methods that are called to start with, the rest are just hooks into the javascript methods to display various things, but nothing is called (like this) prior to this point. And on this specific form, I'm only displaying, not allowing end-users to manipulate the data in any way.
The DrawAreaOverlay method (JS) is responsible for the poly drawing (please excuse the state of the code, I've been ripping it apart trying to figure this out!):
function DrawAreaOverlay(area, col)
{
if(area.Count <= 0)
{
CreateNewArea(0, 0);
return;
}
var coordsString = "";
var areaCoords = [];
overlayLayer[overlayCount] = new Array();
for(var j=0; j<area.Count; j++)
{
areaCoords.push(new google.maps.LatLng(area.Item(j).lat, area.Item(j).lng));
}
var poly = new google.maps.Polygon({
paths: areaCoords,
strokeColor: '#'+col,
strokOpacity: 0.35,
strokeWeight: 2,
fillColor: '#'+col,
fillOpacity: 0.25,
geodesic: false,
editable: canEdit,
draggable: canDrag,
map: map
});
poly.getPaths().forEach(function(path, index){
google.maps.event.addListener(path, 'set_at', function(){
var arrayOfPoints = new Array();
arrayOfPoints = poly.getPath();
coordsString = "";
for(var i=0; i<arrayOfPoints.length; i++)
{
coordsString += poly.getPath().getAt(i).lat() + ", " + poly.getPath().getAt(i).lng() + "|";
}
window.external.AreaPointMoved(coordsString.substring(0, coordsString.length -1));
});
});
// INSERTION OF NEW VERTICES ALONG THE POLYGON EDGES //
poly.getPaths().forEach(function(path, index){
google.maps.event.addListener(path, 'insert_at', function(){
var arrayOfPoints = new Array();
arrayOfPoints = poly.getPath();
coordsString = "";
for(var i=0; i<arrayOfPoints.length; i++)
{
coordsString += poly.getPath().getAt(i).lat() + ", " + poly.getPath().getAt(i).lng() + "|";
}
window.external.AreaPointMoved(coordsString.substring(0, coordsString.length -1));
});
});
debugger;
//if(map == null)
//{
// makeMeANotNullMap(zoomLevel, latitude, longitude);
// overlayLayer[overlayCount] = new Array();
//}
poly.setMap(map);
overlayLayer[overlayCount].push(poly);
overlayCount++;
//alert("I'll work now, but why?");
//window.external.DoNothing();
}
Now the REALLY weird part. If I uncomment the alert box in JS (the: I'll work now, but why? alert) each map renders wonderfully. So something clearly happens to the map once the alert box has been dismissed. It's this missing link I'm after. But I can't fathom it.
Without the alert box, interestingly, the 2nd and 3rd initialisations of the map controls, map is sometimes null. I know this, because I've setup VS to debug the script. So you can drag each one (vigorously) and get the attached image above outcome, where the poly has drawn, but you can't see it.
Any help is greatly appreciated. I don't have a clue why this is happening.

Help with Arrays and the Google Maps API

I have a google maps api function place markers which I'm using from the tutorial found here:Google Maps API with JQuery
By any means, I had to modify the javascript to account for my application. I'm pulling markers from an XML file like before, though this time I'm getting multiple requests, and multiple standard deviation, time to serve, and means for these requests. I've set up the XML to have these with a counter appended to the tag, but it looks like it's not rendering into an array correctly.
To note, I've never used Javascript, and am mostly flying by the seat of my pants on this, so if it's an atrocity of Javascript, feel free to let me know, the entire generation of the XML is in Python.
Sample of the XML: (I apologize, I don't know how to show < or > on stack overflow without it simply hiding it as a tag. Around each "markers" "marker" "name" "requestX" "timetoserveX" etc. is the < and > for tags in XML.
markers
marker
name Simpletown, CA /name
request0 /resource/ /request0
timetoserve0 .001 Seconds to serve request /timetoserve0
mean0 .5309 Mean in seconds /mean0
std_dev0 .552 Standard Deviation in Seconds /std_dev0
request1 /resource2/ /request1
timetoserve1 0.015626 Seconds to serve request /timetoserve1
mean1 0.0011 Mean in seconds /mean1
std_dev1 0.004465 Standard Deviation in Seconds /std_dev1
/marker
/markers
MYMAP.placeMarkers = function(filename) {
$.get(filename, function(xml){
$(xml).find("marker").each(function(){
var name = $(this).find('name').text();
var count = 0;
var requeststring = 'request' + Integer.toString(count)
var request = new Array();
var timetoserve = new Array();
var mean = new Array();
var std_dev = new Array();
var timetoservestring = 'timetoserve' + Integer.toString(count);
var meanstring = 'mean' + Integer.toString(count);
var std_devstring = 'std_dev' + Integer.toString(count);
while ($(this).find(requeststring).text()){
timetoservestring = 'timetoserve' + Integer.toString(count);
meanstring = 'mean' + Integer.toString(count);
std_devstring = 'std_dev' + Integer.toString(count);
request[count] = $(this).find(requeststring).text();
timetoserve[count] = $(this).find(timetoservestring).text();
mean[count] = $(this).find(meanstring).text();
std_dev[count] = $(this).find(std_devstring).text();
count++;
requeststring = 'request' + Integer.toString(count)
}
// create a new LatLng point for the marker
var lat = $(this).find('lat').text();
var lng = $(this).find('lng').text();
var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
// extend the bounds to include the new point
MYMAP.bounds.extend(point);
var marker = new google.maps.Marker({
position: point,
map: MYMAP.map
});
var infoWindow = new google.maps.InfoWindow();
var html = ""
for (i=0;i<count;i++){
html=html+'<strong>'+name+'</strong.><br />'+request[i]+'<br />'+timetoserve[i]+'<br />'+mean[i]+'<br />'+std_dev[i]+<br />;
//var html='<strong>'+name+'</strong.><br />'+request+'</strong.><br />'+timetoserve+'</strong.><br />'+mean+'</strong.><br />'+std_dev;
}
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(MYMAP.map, marker);
});
MYMAP.map.fitBounds(MYMAP.bounds);
});
});
}
With the updates, it's not longer having the array issues it looks like, even though I am getting the map to render at this point. The "Show Markers" button is not populating the map with markers. Running FireBug with this seems to only spew endless amounts of "Break on error" hits and warnings for jQuery.
var request[count] = $(this).find(requeststring).text();
var timetoserve[count] = $(this).find(timetoservestring).text();
var mean[count] = $(this).find(meanstring).text();
var std_dev[count] = $(this).find(std_devstring).text();
to
request[count] = $(this).find(requeststring).text();
timetoserve[count] = $(this).find(timetoservestring).text();
mean[count] = $(this).find(meanstring).text();
std_dev[count] = $(this).find(std_devstring).text();
-assuming these are the arrays that are not working correctly for you.
If I may make a suggestion (RE your comment this morning):
while ($(this).find(requeststring).text()){
//...omitted
}
if you were to rename all your tags to the same thing and give them an id attribute (which is valid in xml) you can do this:
var requests = $(this).find('request');
var timetoserves = $(this).find('timetoserve');
// etc...
for (var i=0; i<requests.length; i++) {
request[i] = requests.eq(i).text();
timetoserve[count] = timetoserves.eq(i).text();
//etc...
}
which would probably provide better performance.

Google Maps API: Create a store locator

Today I am trying to make a store locator using google maps' api.
The store locator is to be set up like so:
two areas, one with a map containing all the stores in a given area (measured in a selectable radius from a center point), and one area with a list of all the stores on the map, their information, and of course a link to their website. When a person clicks on the name of the store on the store list, it centers upon the store in the map, and opens an infoWindow above the store marker.
I have a javascript variable to which I have taken pains to assign some json data from a php script (which is selecting this data on the fly from a database)
locations = [{"siteurl":"http:\/\/localhost.localdomain\/5","address":"260 Test St","city":"Brooklyn","state":"New York","zip_code":"11206"},{"siteurl":"http:\/\/localhost.localdomain\/4","address":"3709 Testing St.","city":"Austin","state":"Texas","zip_code":"78705"}];
Now, I know there are 5 different functions I need to run, listed below with their apparent use:
geocoder.getLocations : Used to
convert address data (from the json
object) into latitude and longitude
data object
addElementToList :
Used to add address information to
the list of stores, and bind the
centerOnStore function to onclick
centerOnStore when a store list item is clicked in the list area, this function center's upon the store that has been clicked on in the map area. This function also opens an infoWindow above the centered upon store.
placeMarker the function to place a marker on the map, called once the geocoder returns latitudeLongitude objects
eventListener this is tied up somehow in the clicking of a list item and it's further centering the map upon the store in question
Well, i am out of my league it would appear. I am just now learning about javascript closures, and I think these may be necessary, but I can't quite understand them. I need to figure out some way to get all these functions into a working order, passing information back and forth to each other, and create a store locator
.
Here is what I've got so far, but there is something very wrong with it.
var map = null;
var geocoder = null;
var locations = null;
var center_on = null;
var zoom_level = null;
var markerList = [];
function initialize()
{
if(GBrowserIsCompatible())
{
// Assign vars
map = new GMap2(document.getElementById("map_canvas"));
geocoder = new GClientGeocoder();
locations = <?php echo(json_encode($my_vars['locations'])); ?>;
center_on = "<?php echo($my_vars['center_on']); ?>";
zoom_level = <?php echo($my_vars['zoom_level']); ?>;
var currentLocation = 0;
geocoder.getLatLng(center_on, function(myPoint)
{
map.setCenter(myPoint, zoom_level);
});
map.setUIToDefault();
var list = document.getElementById('center_list');
for(var i = 0; i < locations.length; i++)
{
var address = locations[i]['address'] + ', ' + locations[i]['city'] + ' ' + locations[i]['state'] + ', ' + locations[i]['zip_code'];
geocoder.getLocations(address, addAddressToMap);
}
}
function addAddressToMap(response) {
if (!response || response.Status.code != 200) {
currentLocation++;
} else {
var place = response.Placemark[0];
var point = new GLatLng(place.Point.coordinates[1],
place.Point.coordinates[0]);
marker = new GMarker(point);
GEvent.addListener(marker, 'click', function(){
this.openInfoWindowHtml("<strong>" + place.address + "</strong><br /><a href='" + locations[currentLocation]['siteurl'] + "'>" + locations[currentLocation]['siteurl'] + "</a>");
});
map.setCenter(point, 13);
markerList.push(marker);
map.addOverlay(marker);
li = document.createElement('li');
li.innerHTML = "<strong>" + place.address + "</strong>";
li.setAttribute('onclick', 'center_on_center(' + place.Point.coordinates[1] + ',' + place.Point.coordinates[0] + ')');
li.setAttribute('id', 'center_');
li.style.fontSize = '1.4em';
document.getElementById('center_list').appendChild(li);
// alert(currentLocation) here says 0,0,0,0
currentLocation++;
// alert(currentLocation) here says 1,2,3,4
}
}
}
I am sorry for the wall of code. I can't think anymore. I had no idea this would be so difficult. No idea at all.
if I alert currentLocation in the line before I increment it, it's always 0. but If I alert it in the line after I increment it, it's '1,2,3,4' etc. This goes against everything I know about computers.
Forget about closures for a moment. You can dive into those once you get a working app. I think you're goal at this point to should be to just get something that accomplishes what you want.
To me, it seems like the only piece you're missing is the idea of a callback function. For instance, addElementToList would be passed as the callback argument to geocoder.getLocaitons. The way it works is that when getLocations() finishes, it calls addElementToList and supplies the result from getLocations() as an argument to addElementToList. The code for addElementToList will then add your store location to the map as a marker and add a new element to your html list with the store's name or address or whatever.
Take a look at this blog post for a simple example using a callback: Introducing Google's Geocoding Service.
The last part, centering on a specific store, can be done (as you suggested) with event listeners. You can set up a listener for clicks on the markers and also for clicks on your list. When you add a marker, you can also add an event listener on it. It'd be nice if you could set one listener for all markers on the map but I'm not familiar enough with google's API to know if this is possible.
What is your source for that information? placeMarker certainly doesn't ring a bell. The Google Maps API reference (complete with examples!) is available at http://code.google.com/apis/maps/documentation/reference.html
Based on your comment to #Rushyo's answer- it seems like you know enough about Javascript and the Google Maps API to construct those functions. I'm a little confused as to what you're looking for.
I would suggest however, that you add lat/lon coordinates to your database in the first place. You shouldn't have to geocode the addresses every time the map is loaded.
Update: In response to your comment below, here is the code you referenced - along with the addAddressToMap() function called by the Geocoder. It creates a marker for each address and adds it to the array markerList. You can then access the markers in that array later, since we initialized it outside the scope of the addAddressToMap() function.
for(var i = 0; i < locations.length; i++) {
var address = locations[i]['address'] + ', ' + locations[i]['city'] + ' ' + locations[i]['state'] + ', ' + locations[i]['zip_code'];
geocoder.getLocations(address, addAddressToMap);
}
var markerList = new array();
function addAddressToMap(response) {
if (!response || response.Status.code != 200) {
alert("\"" + address + "\" not found");
} else {
place = response.Placemark[0];
point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
marker = new GMarker(point);
markerList.push(marker);
map.addOverlay(marker);
}
}
Update 2: In response to the code you posted in your question above, you're probably getting random numbers in currentLocation because of the asynchronous nature of the Geocoder. Remember that your getLocations() function will send requests for every location in the array before it gets any responses back.
I'm creating a new answer, since my other answer is getting messy.
In order to get proper closure, you'll need to create a separate function to make the geocoder request. The following code will allow you to assign the desired infoWindow text to each marker.
for(var i = 0; i < locations.length; i++) {
var address = locations[i]['address'] + ', ' + locations[i]['city'] + ' ' + locations[i]['state'] + ', ' + locations[i]['zip_code'];
var text = locations[i]['address']; // or whatever you want the text to be
getLocation(address, text);
}
...
function getLocation(address, text) {
geocoder.getLocations(address, function(response) {
var place = response.Placemark[0];
var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
marker = new GMarker(point);
marker.bindInfoWindowHtml(text); // note that if you want to use GEvent.addListener() instead - you'll need to create another function to get proper closure
map.addOverlay(marker);
});
}
For more info on closure in Google maps, see these questions:
One
Two
Three

Categories