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
}
Related
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>
I am still relatively new to Google Maps API and JS so this might (probably)
have a simple answer.
I am now returning all places within a certain radius from where my location
is set but I want to be more specific such as only plant nursery's, fuel stations and gyms and only display those markers.
Sorry about the long code block, here is a JSBin if you'd prefer
https://jsbin.com/yodolexece/edit?html,js,output
Thanks in advance.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Locator</title>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBdodiLO598_RD8_NYXK7nBKNA9Fhx_uBQ&libraries=places,geometry&.js"></script>
<script
src="https://code.jquery.com/jquery-3.1.1.js"
integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
crossorigin="anonymous"></script>
</head>
<body>
<input id="findMe" type="button" value="find closest place">
<div id="map-canvas" style="height:500px;"></div>
</body>
</body>
</html>
JS:
<script>
jQuery(function($) {
var $overlay = $('.overlay'),
resize = true,
map;
var service;
var marker = [];
var pos;
var infowindow;
var placeLoc
function initialize() {
var mapOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
$('#findMe').data('pos', pos);
var request = {
location: pos,
radius: 1000,
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'You Are Here'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function callback(results, status) {
var markers = [];
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
markers.push(createMarker(results[i]));
}
}
$('#findMe').data('markers', markers);
}
}
function createMarker(place) {
placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
type: ['store'],
position: place.geometry.location,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8,
fillColor: '00a14b',
fillOpacity: 0.3,
fillStroke: '00a14b',
strokeWeight: 4,
strokeOpacity: 0.7
},
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
return marker;
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
$('#show').click(function() {
$overlay.show();
if (resize) {
google.maps.event.trigger(map, 'resize');
resize = false;
}
});
$('.overlay-bg').click(function() {
$overlay.hide();
});
$("#findMe").click(function() {
var pos = $(this).data('pos'),
markers = $(this).data('markers'),
closest;
if (!pos || !markers) {
alert('pos or markers not set yet');
return;
}
$.each(markers, function() {
var distance = google.maps.geometry.spherical.computeDistanceBetween(this.getPosition(), pos);
if (!closest || closest.distance > distance) {
closest = {
marker: this,
distance: distance
}
}
});
if (closest) {
google.maps.event.trigger(closest.marker, 'click')
}
});
});
</script>
Its quite simple. You need to pass an array of types that you need to edit your request with a new attribute called types to filter. Ex types: ['bank', 'gym']
Code Block below and I will attached a modified version of your JS Bin
JS Bin
Places types can be find from the links below
Place Types
Google Places API Documentation - developers.google.com/maps/documentation/javascript/places#place_search_requests
var request = {
location: pos,
radius: 1000,
types: ['bank', 'gym']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
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>
Hi i have create a web application in which i can show distance between two place on map using google V3 api and in other web application i have created animation drop marker which i can move on the map how can i combine these two. here is my code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Direction2.aspx.cs" Inherits="Direction2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
var latlng = new google.maps.LatLng(51.764696, 5.526042);
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "My location"
});
}
function calcRoute() {
var start = document.getElementById("routeStart").value;
var end = "51.764696,5.526042";
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:710px; height:300px"></div>
<form action="" onsubmit="calcRoute();return false;" id="routeForm">
<input type="text" id="routeStart" value=""/>
<input type="submit" value="Route plannen"/>
<div id="directionsPanel"></div>
</form>
</body>
</html>
And for animation i use this code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Drop.aspx.cs" Inherits="Drop" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Drop</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var stockholm = new google.maps.LatLng(59.32522, 18.07002);
var parliament = new google.maps.LatLng(59.327383, 18.06747);
var marker;
var map;
function initialize() {
var mapOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: stockholm
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
marker = new google.maps.Marker({
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
position: parliament
});
google.maps.event.addListener(marker, 'click', toggleBounce);
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
</script>
</head>
<body onload="initialize()" onunload="Gunload()">
<form id="form1" runat="server">
<div id="map_canvas" style="width:525px; height:237px;">
</div>
</form>
thanks in advance
To change the name of the start or destination city when you move the marker, you need to find the start and end coordinates of the directions and use googles geocoder to find the name of the locations.
You need to listen for the 'directions_changed' event and find the start and end latlngs.
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
var directions = this.getDirections();
var overview_path = directions.routes[0].overview_path;
var startingPoint = overview_path[0];
var destination = overview_path[overview_path.length - 1];
if (typeof startLatlng === 'undefined' || !startingPoint.equals(startLatlng)) {
startLatlng = startingPoint;
getLocationName(startingPoint, function(name) {
routeStart.value = name;
});
}
if (typeof endLatlng === 'undefined' || !destination.equals(endLatlng)) {
endLatlng = destination;
getLocationName(destination, function(name) {
routeEnd.value = name;
});
}
});
To get the name of the markers location use the following function (I put this together quickly, will need more testing)
function getLocationName(latlng, callback) {
geocoder.geocode({location: latlng}, function(result, status) {
if (status === google.maps.GeocoderStatus.OK) {
var i = -1;
// find the array index of the last object with the locality type
for (var c = 0; c < result.length; c++) {
for (var t = 0; t < result[c].types.length; t++) {
if (result[c].types[t].search('locality') > -1) {
i = c;
}
}
}
var locationName = result[i].address_components[0].long_name;
callback(locationName);
}
});
}
By doing it this way, you can't set a click event to the map markers applied to the map, which means you can't have your marker bouncing animation. If you need the marker animation, then you would have to suppress the markers in the directions service and display your own markers. When the marker is dragged you would have to recalculate the directions and then use the getLocationName function with the markers position.
Here is a working demo.
Should be enough to get you closer to what you want.
EDIT I've updated the code to change the value of the start or end input box when dragging.
The marker drag event will fire hundreds of times when only dragging a small distance, so we need to set a timer as not to request to many geocodes.
I've put together a working demo of this here: http://jsfiddle.net/SMEAD/6/
We needed to use our own markers so when initializing the DirectionsRenderer we need to pass in the suppressMarkers option
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
We only need to listen for directions changed once and set the markers.
google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed', function() {
var directions = this.getDirections();
var overview_path = directions.routes[0].overview_path;
var startingPoint = overview_path[0];
var destination = overview_path[overview_path.length - 1];
addMarker(startingPoint, 'start');
addMarker(destination, 'end');
});
The work horse function is addMarker. This sets up the events we need to update the input boxes and recalculate the directions.
function addMarker(position, type) {
var marker = new google.maps.Marker({
position: position,
draggable: true,
animation: google.maps.Animation.DROP,
map: map
});
marker.type = type; // probably not a good idea to do this.
google.maps.event.addListener(marker, 'drag', function() {
var marker = this;
clearTimeout(dragTimer);
dragTimer = setTimeout(function() {
getLocationName(marker.getPosition(), function(name) {
if (marker.type === 'start') {
routeStart.value = name;
} else {
endStart.value = name;
}
});
}, 250);
});
google.maps.event.addListener(marker, 'dragend', function() {
calcRoute(startMarker.getPosition(), endMarker.getPosition());
});
if (type === 'start') {
startMarker = marker;
} else {
endMarker = marker;
}
}
I am pretty experienced when it come to php mysql, but javascript has got me scratching my head. I am trying to add google maps to my website to show where picture in my database were taken. I got the static google map to work, but it will only display 37 markers due to the url character limitations. I followed the tutorial at google maps api docs, and i have a map that will display all the coordinates for the images in my database. My problem is that i cannot for the life of me figure out how to get the map to auto center and auto zoom to fit all of my markers. my test website for my map is at maptest. I found this tutorial on how to auto center/zoom my map by no matter where i put his code i get errors. this is the code i have for my map that does not auto zoom/center:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps AJAX + mySQL/PHP Example</title>
<script src="http://maps.google.com/maps/api/js? key=AIzaSyDnMkDkoCHNE7BG4eobjeMJdWWZtdZvzeg&sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(42.293564,-39.07617),
zoom: 2,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml3.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
//var address = markers[i].getAttribute("address");
//var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>";
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
//icon: icon.icon,
//shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 600px; height: 400px"></div>
</body>
</html>
Tried this?
var fitToMarkers = function(markers) {
var bounds = new google.maps.LatLngBounds();
var length = markers.length;
for (var i = 0; i < length; i++) {
bounds.extend(new google.maps.LatLng(markers[i].lat, markers[i].lng));
map.fitBounds(bounds);
}
};