I'm trying to replicate similar functionality in Google Maps where you right click & it gives an option to have directions to/from that point. The struggle I'm having is interacting with the infowindow & passing the lat/longs back.
The listener creates the infowindow fine. but I can;t work out how to pass the lat/longs back into the javascript (either as an origin or destination) so as I can then use it in the directions service. I'll eventually have a second marker which will populate the other value in origin/destination. Once the array has two values I'll call the directions service.
All the examples I've seen have required some form of manual input to define the second part of the address.
I'm still very new to this, so please go easy on me; I've tried my best to provide the most trimmed down sample code to demonstrate my issue.
var mapCanvas = "map-canvas",
map,
infowindow = new google.maps.InfoWindow(),
LocationArr = [],
o;
google.maps.event.addDomListener(window, "load", function(){
map = new google.maps.Map(document.getElementById(mapCanvas), {zoom: 13,center: {lat: 53.4723272,lng: -2.2935022}});
var geocoder = new google.maps.Geocoder;
google.maps.event.addListener(map, "click", function(o) {
LocationArr.push(o.latLng);
var a = new google.maps.Marker({
position: o.latLng,
map: map,
});
var content = "<input type='button' name='DirFrom' value='Directions from here' onclick='DirFromHere()' id='Dir_From'>"
+ "<input type='button' name='DirTo' value='Directions to here' onclick='DirToHere()' id='Dir_To'>"
infowindow.setContent(content);
infowindow.open(map, a);
});
});
function DirFromHere(LocationArr){
console.log(LocationArr.length);
}
function DirToHere(LocationArr){
LocationArr=[];
}
html, body {
height: 100%;
width: 100%;
}
#map-canvas {
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
}
<html>
<head>
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script src="js/aqrouting.js"></script>
</body>
</html>
Here is a simple example of how you can do that, using vanilla Javascript only. Code is commented. That should be enough to understand how it works.
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map, infowindow;
var start, end, pos;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
// Map options
var center = new google.maps.LatLng(45.07, 7.67);
var myOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
}
// Create map
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
directionsDisplay.setMap(map);
// Create infowindow
infowindow = new google.maps.InfoWindow({
content: '',
map: map
});
// Listen for map click
google.maps.event.addListener(map, 'click', function(e) {
// Save current position
pos = e.latLng;
// Set infowindow position and open
infowindow.setPosition(pos);
infowindow.open(map)
});
// Create infowindow buttons
let btnFrom = document.createElement("button");
btnFrom.id = 'directionsFrom';
btnFrom.innerHTML = 'Directions from here'
let btnTo = document.createElement("button");
btnTo.id = 'directionsTo';
btnTo.innerHTML = 'Directions to here'
// Add DOM listener to DIRECTIONS FROM button
google.maps.event.addDomListener(btnFrom, 'click', function() {
// Set start position
start = pos;
});
// Add DOM listener to DIRECTIONS TO button
google.maps.event.addDomListener(btnTo, 'click', function() {
// Set end position
end = pos;
// Check that start and end position both are an instance of LatLng
if ((start instanceof google.maps.LatLng) && (end instanceof google.maps.LatLng)) {
// We have a start and end position so we can request directions
getDirections();
}
});
// Add the 2 buttons in a DIV
let contentDiv = document.createElement('div');
contentDiv.appendChild(btnFrom);
contentDiv.appendChild(btnTo);
// Add the DIV as the infowindow content
infowindow.setContent(contentDiv);
}
// Make a Directions request and display it on the map
function getDirections() {
var method = 'DRIVING';
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode[method]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
// Close infowindow
infowindow.close();
}
});
}
initialize();
#map-canvas {
height: 150px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk
"></script>
Related
I wrote a little html page in order to display pushpins on a map.
I give some address to my webpage, then I use the geocoding() and i display pushpins.
Then, I would like to add the google.maps.Animation.DROP with a timeout like explained on the Google Maps API page. ( https://developers.google.com/maps/documentation/javascript/examples/marker-animations-iteration?hl=fr)
On the Google Maps API page, the sample code directly uses the coordinates. It's simple.
In my case, I need to use before the geocoding() to get points, then display the pushpins.
I really don't understand but I'm unable to use this Drop animation with timeout using geocoding. I used the debugger view in Chrome, and I don't understand.
Here is my code, i tried to do as simple as possible :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
width:100%;
height:100%;
}
</style>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=initMap">
</script>
</head>
<body>
<div id="map" ></div>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
//<![CDATA[
var infoWindow;
var map;
var geocoder;
var bounds;
var TbCoordonnees = [];
var TbMarkers = [];
var AdresseTiersTb = [];
function initMap()
{
geocoder = new google.maps.Geocoder();
var optionsCarte = {
zoom: 8,
center: new google.maps.LatLng(48.5, 2.9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), optionsCarte);
bounds = new google.maps.LatLngBounds();
infoWindow = new google.maps.InfoWindow({});
// EXAMPLE :
AdresseTiersTb.push("39 Boulevard de Courtais, 03100 Montluçon");
AdresseTiersTb.push("Place de l'Hôtel de ville, 13100 Aix-en-Provence");
AdresseTiersTb.push("55 Rue du Faubourg Saint-Honoré, 75008 Paris");
AdresseTiersTb.push("Place des Buisses, 59000 Lille");
for (var i = 0; i < AdresseTiersTb.length; i++)
{
geocodeAddress(AdresseTiersTb[i],i*200);
}
}
function geocodeAddress(address,timeout)
{
geocoder.geocode(
{'address': address},
function(results, status)
{
if((results != null) && (status == google.maps.GeocoderStatus.OK))
{
var marker = createMarker(address,timeout,results);
}
else
{
alert("geocode failed on "+address+", status="+status);
}
}
);
}
function createMarker(address,timeout,results)
{
var marker;
window.setTimeout(function() {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,animation: google.maps.Animation.DROP
});},timeout);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds)
map.panToBounds(bounds);
map.setCenter(bounds.getCenter());
var infocontent = address;
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(infocontent);
infoWindow.open(map, marker);
});
return marker;
}
function listenMarker (marker, info)
{
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(info);
infoWindow.open(map, this);
});
}
</script>
The problem is the var marker appear to be undefined, so no pushpins once pushpin is displayed instead of three. I don't know why but when I look in debug mode I don't understand how the geocoding is executed. Very strange.
You can't return a useful value of the marker variable from the asynchronous setTimeout callback function (where it is created and added to the map). The function returns the variable immediately (before it is defined by the callback of the setTimeout call (which runs some time later). The marker is also not defined when you are adding the click event listener.
proof of concept fiddle
code snippet:
var infoWindow;
var map;
var geocoder;
var bounds;
var TbCoordonnees = [];
var TbMarkers = [];
var AdresseTiersTb = [];
function initMap() {
geocoder = new google.maps.Geocoder();
var optionsCarte = {
zoom: 8,
center: new google.maps.LatLng(48.5, 2.9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), optionsCarte);
bounds = new google.maps.LatLngBounds();
infoWindow = new google.maps.InfoWindow({});
// EXAMPLE :
AdresseTiersTb.push("Versailles, FR");
AdresseTiersTb.push("Paris, FR");
AdresseTiersTb.push("Sens, FR");
for (var i = 0; i < AdresseTiersTb.length; i++) {
geocodeAddress(AdresseTiersTb[i], i * 200);
}
}
function geocodeAddress(address, timeout) {
// function closure on address.
geocoder.geocode({
'address': address
},
function(results, status) {
if ((results != null) && (status == google.maps.GeocoderStatus.OK)) {
createMarker(address, results[0].geometry.location, timeout);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds)
} else {
alert("geocode failed on " + address + ", status=" + status);
}
}
);
}
function createMarker(address, latLng, timeout) {
// function closure on address, latLng
window.setTimeout(function() {
var marker = new google.maps.Marker({
map: map,
position: latLng,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', (function(marker, address) {
// function closure on marker, address
return function() {
infoWindow.setContent(address);
infoWindow.open(map, marker);
}
})(marker, address));
}, timeout);
}
function listenMarker(marker, info) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(info);
infoWindow.open(map, this);
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
This is my first post so i'm sorry if it has been asked before.
I have a form users fill out on mobile devices which captures there longitude and latitude using JavaScript geolocation. this isn't always the most accurate so I am trying to combine geolocation and google map draggable pin.
So the user opens the page, geolocation enters the current lon and lat in the script below, if its wrong they can then drag the pin to the right location which updates the text fields.
I have tried every thing and have had mixed results...if someone could help me out that would be great.
I hope this makes sense...if not im happy to explain more
The script below enables you to drag the pin and updates the two text field with the lon and lat.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input type="text" id="latitude" placeholder="latitude">
<input type="text" id="longitude" placeholder="longitude">
<div id="map" style="width:500px; height:500px"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
var $latitude = document.getElementById('latitude');
var $longitude = document.getElementById('longitude');
var latitude = 50.715591133433854
var longitude = -3.53485107421875;
var zoom = 7;
var LatLng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: zoom,
center: LatLng,
panControl: false,
zoomControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: 'Drag Me!',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLng = marker.latLng;
$latitude.value = latLng.lat();
$longitude.value = latLng.lng();
});
}
initialize();
</script>
</body>
</html>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
function initialize() {
var map;
var position = new google.maps.LatLng(50.45, 4.45); // set your own default location.
var myOptions = {
zoom: 15,
center: position
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
// We send a request to search for the location of the user.
// If that location is found, we will zoom/pan to this place, and set a marker
navigator.geolocation.getCurrentPosition(locationFound, locationNotFound);
function locationFound(position) {
// we will zoom/pan to this place, and set a marker
var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// var accuracy = position.coords.accuracy;
map.setCenter(location);
var marker = new google.maps.Marker({
position: location,
map: map,
draggable: true,
title: "You are here! Drag the marker to the exact location."
});
// set the value an value of the <input>
updateInput(location.lat(), location.lng());
// Add a "drag end" event handler
google.maps.event.addListener(marker, 'dragend', function() {
updateInput(this.position.lat(), this.position.lng());
});
}
function locationNotFound() {
// location not found, you might want to do something here
}
}
function updateInput(lat, lng) {
document.getElementById("my_location").value = lat + ',' + lng;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#map-canvas {
width: 500px;
height: 400px;
}
</style>
<div id="map-canvas"></div>
Location:<br>
<input id="my_location" readonly="readonly">
You can get the user location from the navigator.geolocation:
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
latPosition = position.coords.latitude;
longPosition = position.coords.longitude;
});
Then you can use these values to fill in your coordinates inputs and/or to place a marker on the map, as in my demo below.
JSFiddle demo
I have been studying Google Maps and I would like to accomplish the following goal:
1) drop markers one by one;
2) delete last marker (so just one is in viewport)
3) drop next marker
4) Have info window opened in each marker
5) repeat operation
I have been trying to twist the code for animations AND trying to set map null (setMap(null)), but with no success after calling the drop function. Any suggestion on how to do that?
Bottom line: have something like this. Of course this has one big extra step of difficult, which is pulling data from database.
Here is the code.
Any help will be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Marker animations with <code>setTimeout()</code></title>
<style>
#map-canvas{
width:600px;
height:600px;
position: "absolute";
top: 0px;
left: 0px;
overflow: "hidden";
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var berlin = new google.maps.LatLng(52.520816, 13.410186);
var neighborhoods = [
new google.maps.LatLng(52.511467, 13.447179),
new google.maps.LatLng(52.549061, 13.422975),
new google.maps.LatLng(52.497622, 13.396110),
new google.maps.LatLng(52.517683, 13.394393)
];
var markers = [];
var iterator = 0;
var Marker;
var map;
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: berlin
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
drop();
}
function drop(){
for (var i = 0; i < neighborhoods.length; i++) {
var m = neighborhoods[i];
(function(n){
setTimeout(function() {
addMarker(n);
}, i * 500);
}(m));
}
}
function addMarker() {
markers.push(new google.maps.Marker({
position: neighborhoods[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP
}));
iterator++;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html
>
Did you want only one marker to display at a time?
Here is some code that does that:
$(function() {
var BERLIN = new google.maps.LatLng(52.520816, 13.410186);
var NEIGBORHOODS = [
new google.maps.LatLng(52.511467, 13.447179),
new google.maps.LatLng(52.549061, 13.422975),
new google.maps.LatLng(52.497622, 13.396110),
new google.maps.LatLng(52.517683, 13.394393)];
var map = null;
var marker = null;
var index = 0;
var infoWindow = null;
function createMap() {
return new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: BERLIN,
zoom: 12
});
}
function dropMarker(map, pos) {
return new google.maps.Marker({
map: map,
position: pos,
draggable: false,
animation: google.maps.Animation.DROP
});
}
function changeMarker() {
if (marker) {
infoWindow.close();
marker.setMap(null);
}
var pos = NEIGBORHOODS[index];
marker = dropMarker(map, pos);
infoWindow.setContent('lat: ' + pos.lat() + '<br />' + 'lng: ' + pos.lng());
setTimeout(function () {
infoWindow.open(map, marker);
}, 500);
index = (index + 1) % NEIGBORHOODS.length;
setTimeout(function () {
changeMarker();
}, 2000);
}
map = createMap();
infoWindow = new google.maps.InfoWindow()
changeMarker();
});
Notice how the changeMarker() function does its work, then usessetTimeout() to call itself again. This sets up an infinite loop where changeMarker() is called every two seconds.
I used setTimeout() to delay the showing of the Info Window by a half second so it does not appear until the drop is finished.
jsfiddle demo
I'm new to both Google Maps and Javascript but have to get this issue solved! I have an .html file with a google map of our client's location loaded into the map_canvas div. Through tutorials, I have been able to figure out how to write enough Javascript to get the map to function, have a custom marker and and infowindow that pops up when you click on it. The only part left is to have a link inside the infowindow that says "directions to here" and there's a text field that the user can type in their starting address. I'm seeing plenty of documentation to help me write my own code on the Google Developer's site but I am not advanced enough to do this. Can anyone help me figure out how to do this? Here is my Javascript:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize()
{
var latlng = new google.maps.LatLng(33.929011, -84.361);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(33.929011, -84.361),
map: map,
title: 'Atlanta/Sandy Springs',
clickable: true,
icon: 'images/mapmarker.png'
});
var infowindow = new google.maps.InfoWindow({
content: 'client address'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
</script>
There are several pieces I added. First, you need a better HTML form inside the infowindow, since I only put in the basic parts and it won't respond when you press Enter.
Next, I added a geocoder because the directions Service won't take "human readable" addresses, only latLng coordinates. The geocoder converts the two. Finally, the directions Service and Display are added. The directions text goes into a div (directionsPanel).
See the working fiddle or use this code:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body {
margin: 0;
padding: 0;
height: 100%
}
#map_canvas {
margin: 0;
padding: 0;
width: 50%;
height: 100%
}
#directionsPanel {
position: absolute;
top: 0px;
right: 0px;
width: 50%
}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var directionsService;
var directionsDisplay;
function initialize() {
var latlng = new google.maps.LatLng(33.929011, -84.361);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(33.929011, -84.361),
map: map,
title: 'Atlanta/Sandy Springs',
clickable: true
});
var infowindow = new google.maps.InfoWindow({
content: "Your address: <input id='clientAddress' type='text'>"+
"<input type='button' onClick=getDir() value='Go!'>"
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
geocoder = new google.maps.Geocoder();
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: false
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
function getDir() {
geocoder.geocode({
'address': document.getElementById('clientAddress').value
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var origin = results[0].geometry.location;
var destination = new google.maps.LatLng(33.929011, -84.361);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
} else {
document.getElementById('clientAddress').value =
"Directions cannot be computed at this time.";
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
<div id="directionsPanel"></div>
</body>
</html>
How can i show multiple locations on google map.
I am using this code for google map?
<script type="text/javascript">
$(function() { // when the document is ready to be manipulated.
if (GBrowserIsCompatible()) { // if the browser is compatible with Google Map's
var map = document.getElementById("myMap"); // Get div element
var m = new GMap2(map); // new instance of the GMap2 class and pass in our div location.
var longArray= ("<?php echo $long; ?>").split(',');
var latArray= ("<?php echo $lat; ?>").split(',');
for(i=0;i<longArray.length;i++)
{
m.setCenter(new GLatLng(latArray[i], longArray[i]), 13); // pass in latitude, longitude, and zoom level.
m.openInfoWindow(m.getCenter(), document.createTextNode("This is testing")); // displays the text
}
m.setMapType(G_SATELLITE_MAP); // sets the default mode. G_NORMAL_MAP, G_HYBRID_MAP
var c = new GMapTypeControl(); // switch map modes
m.addControl(c);
m.addControl(new GLargeMapControl()); // creates the zoom feature
}
else {
alert("Upgrade your browser, man!");
}
});
</script>
Refer below code, that worked perfectly fine for me.
The code snippet below will give you an error to provide valid API key i.e. "Google Maps JavaScript API error: InvalidKeyMapError", to resolve this the only thing you need is valid API Key provided by google maps.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Multiple Locations using Google Maps </title>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false"></script>
</head>
<body>
<div id="googleMap" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var locationArray = [
['Pune', 18.5248904, 73.7228789, 1],
['Mumbai', 19.0825223, 72.7410977, 2],
['Ahmednagar', 19.1104918, 74.6728675, 3],
['Surat', 21.1594627, 77.3507354, 4],
['Indore', 22.7242284, 75.7237617, 5]
];
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 8,
center: new google.maps.LatLng(18.5248904,73.7228789),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locationArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locationArray[i][1], locationArray[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locationArray[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
For more details refer here. I hope this is what you are looking for!
setCenter is used to zoom and center the map.. if you want to mark multiple locations you need to create a marker and place it on the map inside your loop.. there's a good set of tutorials here:
http://econym.org.uk/gmap/index.htm
If your question relates to showing multiople disparate locations on a single map then you cant, a map can only be centered on one lat/lng at a time..
Its not entirely clear what you're trying to achieve.
Dunc.
following steps you have to follow.
1. make a list of your addresses in javascript aaray.
2. make a utility function to geocode and then put marker by passing address as arguement.
3. iterate over your addresses array and call your marker utility function.
example: map.jsp ::
it tales input json string that is list of addresses and the converts it to javascript array:
add the jquery and infobox.js by downloading fron google.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script language="JavaScript" src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
<script language="JavaScript" src="js/infobox.js" type="text/javascript"></script>
</head>
<body>
<%
String json=request.getParameter("address");
%>
<input type="hidden" id="json" value="<%=json%>"></input>
<div id="map" style="width: 1250px; height: 500px;" align="center"></div>
<script type="text/javascript" language="JavaScript" src="js/map.js"></script>
<script type="text/javascript">
var jsonvalue=document.getElementById("json").value;
var use=unescape(jsonvalue);
//alert(use);
var obj = eval ("(" + use + ")");
var cobj=obj.center;
var olist=obj.other;
codeproject(cobj.center_add,cobj.center_name);
//alert(cobj.center_name+" and "+cobj.center_add);
for(var i=0;i<olist.length;i++)
{
//alert(olist[i].other_add);
codeAddress(olist[i].other_add,olist[i].other_name);
}
</script>
</body>
</html>
________map.js________
//used by infowindow
//the googlemap code
var geocoder = new google.maps.Geocoder();
//var infowindow = new google.maps.InfoWindow();
var LatLngList = new Array(6);
var i;
var infowindow = new google.maps.InfoWindow();
var markerBounds = new google.maps.LatLngBounds();
var markerarray=new Array();
//making the div for window popup
var boxText = document.createElement("div");
boxText.style.cssText = "border: 2px solid Gray; margin-top: 6px; background: white; padding: 5px;font-weight: bold;color: Gray;";
boxText.innerHTML = " ";
//options array for infobox window
var myOptions = {
map:map,
content : boxText,
disableAutoPan : false,
maxWidth : 0,
pixelOffset : new google.maps.Size( - 140, 0),
zIndex : null,
boxStyle : { background : "url('tipbox.gif') no-repeat", width : "280px" },
closeBoxMargin : "10px 4px 2px 2px", closeBoxURL : "close.gif",
infoBoxClearance : new google.maps.Size(1, 1),
isHidden : false,
pane : "floatPane",
enableEventPropagation : true
};
var infoBox;
function codeproject(address, client) {
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, icon : 'green-dot.png', position : results [0].geometry.location, draggable : false, animation : google.maps.Animation.DROP
});
//bounce the marker
// marker.setAnimation(google.maps.Animation.BOUNCE);
//initialize info box
infoBox = new InfoBox(myOptions);
markerBounds.extend(results[0].geometry.location);
//listeners
google.maps.event.addListener(marker, 'mouseover', function () {
//stop bouncing
// marker.setAnimation(null);
// $("img[src$='iws3.png']").hide();
// infowindow.setContent('<b>' + client + '<\/b><br>'+ results[0].formatted_address);
// infowindow.open(map, this);
boxText.innerHTML = "<br>"+client +"<br>"+results[0].formatted_address;
infoBox.setContent(boxText,marker);
infoBox.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function () {
// infowindow.close();
infoBox.close();
//start bounce
// marker.setAnimation(google.maps.Animation.BOUNCE);
});
//ok end
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
alert("Error Occured during geocode:" + status);
}
// alert('Geocode was not successful for '+client +' the following reason: ' + status);
}
});
}
function codeAddress(address, client) {
// var address = document.getElementById('address').value;
geocoder.geocode( {
'address' : address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// map.setCenter(results[0].geometry.location);
infoBox = new InfoBox(myOptions);
var marker = new google.maps.Marker( {
map : map,
// icon : 'smallpin.png',
position : results[0].geometry.location, draggable : false, animation : google.maps.Animation.DROP
});
//make bounds
//bounce the marker
// marker.setAnimation(google.maps.Animation.BOUNCE);
//initialize info box
markerBounds.extend(results[0].geometry.location);
//listeners
google.maps.event.addListener(marker, 'mouseover', function () {
//stop bouncing
// marker.setAnimation(null);
$("img[src$='iws3.png']").hide();
// infowindow.setContent('<b>' + client + '<\/b><br>'+ results[0].formatted_address + '<\br>');
//infowindow.open(map, this);
boxText.innerHTML = "<br>"+client +"<br>"+results[0].formatted_address ;
infoBox.setContent(boxText,marker);
infoBox.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function () {
// infowindow.close();
//start bounce
infoBox.close();
// marker.setAnimation(google.maps.Animation.BOUNCE);
});
//ok end
}
else {
// alert('Geocode was not successful for '+client +' the following reason: ' + status);
}
});
}
//////////////calling the above two functions
var centerpoint = new google.maps.LatLng(43.652527, - 79.381961);//for ontario canada zoom level-7
//map intializing
var map = new google.maps.Map(document.getElementById('map'),
{
zoom : 4, backgroundColor : '#B5B5B5', draggable : true, center : centerpoint, mapTypeId : google.maps.MapTypeId.ROADMAP
});
///geocoding multiple addresses
//bounce markers
function toggleBounce(mark) {
if (mark.getAnimation() != null) {
mark.setAnimation(null);
}
else {
mark.setAnimation(google.maps.Animation.BOUNCE);
}
}
/////
function putmarker(address,client,lat,lng) {
var position = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker( {
map : map, icon : 'green-dot.png', position : position, draggable : false, animation : google.maps.Animation.DROP
});
//bounce the marker
// marker.setAnimation(google.maps.Animation.BOUNCE);
//initialize info box
infoBox = new InfoBox(myOptions);
markerBounds.extend(position);
//listeners
google.maps.event.addListener(marker, 'mouseover', function () {
//stop bouncing
// marker.setAnimation(null);
// $("img[src$='iws3.png']").hide();
// infowindow.setContent('<b>' + client + '<\/b><br>'+ results[0].formatted_address);
// infowindow.open(map, this);
boxText.innerHTML = "<br>"+client +"<br>"+address;
infoBox.setContent(boxText,marker);
infoBox.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function () {
// infowindow.close();
infoBox.close();
//start bounce
// marker.setAnimation(google.maps.Animation.BOUNCE);
});
//ok end
}