Google maps v3 - Add markers at the center of tiles - google-maps

function initialize() {
var myLatlng;
var mapOptions;
myLatlng = new google.maps.LatLng(29.98439980, -95.34140015);
mapOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function() {
drawRectangle(map);
var result = {"regionList":[{"centerLongitude":-95.34890747070312,"imageIcon":"../images/untested-icon.png","centerLatitude":29.980682373046875},{"centerLongitude":-95.34890747070312,"imageIcon":"../images/untested-icon.png","centerLatitude":29.988117218017578},{"centerLongitude":-95.33389282226562,"imageIcon":"../images/untested-icon.png","centerLatitude":29.980682373046875},{"centerLongitude":-95.33389282226562,"imageIcon":"../images/untested-icon.png","centerLatitude":29.988117218017578}]};
alert(result);
addMarkersAtRegionCenter(map, result);
});
function addMarkersAtRegionCenter(map, result) {
var length = result.regionList.length;
var regionUrl = "drilledDownToRegion.jsp?";
for(var i=0; i<length; i++)
{
var image = result.regionList[i].imageIcon;
//alert("Latitude : " + result.regionList[i].centerLatitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.regionList[i].centerLatitude,result.regionList[i].centerLongitude),
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() {
window.location.href = marker.url;
}
})(marker, i));
}
}
function drawRectangle(map) {
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var numberOfParts = 4;
var tileWidth = (northEast.lng() - southWest.lng()) / numberOfParts;
var tileHeight = (northEast.lat() - southWest.lat()) / numberOfParts;
for (var x = 0; x < numberOfParts; x++) {
for (var y = 0; y < numberOfParts; y++) {
var areaBounds = {
north: southWest.lat() + (tileHeight * (y+1)),
south: southWest.lat() + (tileHeight * y),
east: southWest.lng() + (tileWidth * (x+1)),
west: southWest.lng() + (tileWidth * x)
};
var area = new google.maps.Rectangle({
strokeColor: '#FF0000',
//strokeOpacity: 0.8,
strokeWeight: 2,
//fillColor: '#FF0000',
//fillOpacity: 0.35,
map: map,
bounds: areaBounds
});
}
}
}
}
google.maps.event.addDomListener(window, "load", initialize);
In the above code, I am trying to add markers at the center of each rectangle. But I am not able to add markers. I have hard coded image icon value since I don't have image mentioned in the array.
Thanks in advance for your help.

Related question: Google maps api v3 - divide region into equal parts using tiles
Simpler to add the markers to the centers of the rectangles when you create them:
var centerMark = new google.maps.Marker({
position: area.getBounds().getCenter(),
map: map
});
proof of concept fiddle
To add the markers from the response to the map (the positions in the posted response are not at the center of the squares), this is the same function you posted in your question, it works for me (the blue markers), I modified your click listener to open an infowindow (rather than do a redirect of the page):
function addMarkersAtRegionCenter(map, result) {
var length = result.regionList.length;
var regionUrl = "drilledDownToRegion.jsp?";
for (var i = 0; i < length; i++) {
var image = result.regionList[i].imageIcon;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.regionList[i].centerLatitude, result.regionList[i].centerLongitude),
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
// window.location.href = marker.url;
infowindow.setContent("regionList:" + i + "<br>centLat=" + result.regionList[i].centerLatitude + "<br>centLng=" + result.regionList[i].centerLongitude + "<br>imageIcon=" + result.regionList[i].imageIcon + "<br>" + marker.getPosition().toUrlValue(6));
infowindow.open(map, marker);
}
})(marker, i));
}
}

Related

How to get coordinates in polyline using google map?

I tried to create a polyline in google Maps. It's created and polyline also working fine. but I need when to click polyline to get coordinates. My Scenario(I have three markers in google map.so, three markers used to connect the polyline markerA connect to markerB connect to markerC. when I click polyline in between markerA and makrerB. I need that two markers latitude and longitude). How to achieve this scenario.
My Code
<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="googleMap" style="width:100%;height:400px;"></div>
<script>
function myMap() {
var mapProp= {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var goldenGatePosition = [{lat: 11.0168,lng: 76.9558},{lat: 11.6643,lng: 78.1460},{lat:11.2189,lng:78.1674}];
for(let i=0;i<goldenGatePosition.length;i++){
var marker = new google.maps.Marker({
position: goldenGatePosition[i],
map: map,
title: 'Golden Gate Bridge'
});
}
var flightPath = new google.maps.Polyline({
path:goldenGatePosition,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2
});
flightPath.setMap(map);
var infowindow = new google.maps.InfoWindow();
var codeStr=''
google.maps.event.addListener(flightPath, 'click', function(event) {
infowindow.setContent("content");
// var pathArr = flightPath.getPath()
// for (var i = 0; i < pathArr.length; i++){
// codeStr = '{lat: ' + pathArr.getAt(i).lat() + ', lng: ' + pathArr.getAt(i).lng() + '}' ;
// console.log(codeStr)
// };
console.log(event.latLng)
var length = this.getLength();
var mid = Math.round( length / 2 );
var pos = this.getAt( mid );
console.log(pos)
// infowindow.position = event.latLng;
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCHmYOxkvd4u3rbHqalUSlGOa-b173lygA&callback=myMap"></script>
</body>
</html>
Google Map
Simplest way:
include the google maps geometry library.
use the poly namespace isLocationOnEdge method to detect which segment of the polyline the click was on. Output the two end coordinates of that segment.
isLocationOnEdge(point, poly[, tolerance])
Parameters:
point: LatLng
poly: Polygon|Polyline
tolerance: number optional
Return Value: boolean
Computes whether the given point lies on or near to a polyline, or the edge of a polygon, within a specified tolerance. Returns true when the difference between the latitude and longitude of the supplied point, and the closest point on the edge, is less than the tolerance. The tolerance defaults to 10-9 degrees.
google.maps.event.addListener(flightPath, 'click', function(event) {
// make polyline for each segment of the input line
for (var i = 0; i < this.getPath().getLength() - 1; i++) {
var segmentPolyline = new google.maps.Polyline({
path: [this.getPath().getAt(i), this.getPath().getAt(i + 1)]
});
// check to see if the clicked point is along that segment
if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline,10e-3)) {
// output the segment number and endpoints in the InfoWindow
var content = "segment "+i+"<br>";
content += "start of segment=" + segmentPolyline.getPath().getAt(0).toUrlValue(6) + "<br>";
content += "end of segment=" + segmentPolyline.getPath().getAt(1).toUrlValue(6) + "<br>";
infowindow.setContent(content);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
}
});
proof of concept fiddle
code snippet:
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#googleMap {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<h1>My First Google Map</h1>
<div id="googleMap"></div>
<script>
function myMap() {
var mapProp = {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 5,
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var goldenGatePosition = [{
lat: 11.0168,
lng: 76.9558
}, {
lat: 11.6643,
lng: 78.1460
}, {
lat: 11.2189,
lng: 78.1674
}];
var bounds = new google.maps.LatLngBounds();
for (let i = 0; i < goldenGatePosition.length; i++) {
var marker = new google.maps.Marker({
position: goldenGatePosition[i],
map: map,
title: 'Golden Gate Bridge'
});
bounds.extend(goldenGatePosition[i]);
}
var flightPath = new google.maps.Polyline({
path: goldenGatePosition,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2
});
flightPath.setMap(map);
map.fitBounds(bounds);
var infowindow = new google.maps.InfoWindow();
var codeStr = ''
google.maps.event.addListener(flightPath, 'click', function(event) {
// make polyline for each segment of the input line
for (var i = 0; i < this.getPath().getLength() - 1; i++) {
var segmentPolyline = new google.maps.Polyline({
path: [this.getPath().getAt(i), this.getPath().getAt(i + 1)]
});
// check to see if the clicked point is along that segment
if (google.maps.geometry.poly.isLocationOnEdge(event.latLng, segmentPolyline, 10e-3)) {
// output the segment number and endpoints in the InfoWindow
var content = "segment " + i + "<br>";
content += "start of segment=" + segmentPolyline.getPath().getAt(0).toUrlValue(6) + "<br>";
content += "end of segment=" + segmentPolyline.getPath().getAt(1).toUrlValue(6) + "<br>";
infowindow.setContent(content);
infowindow.setPosition(event.latLng);
infowindow.open(map);
}
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=myMap"></script>

Google maps showing same info window for all markers

I'm looping over an array of properties and create multiple markers on a google map. I'd like each of these markers to have their own info window content. My code looks right to me but it's not working. Can somebody point me in the right direction.
Here is my current code
for (var i = startRow; i < AMdata.property.length; i++) {
var propertyDetails = AMdata.property[i];
var latLng = new google.maps.LatLng(propertyDetails.LATITUDE, propertyDetails.LONGITUDE);
bounds.extend(latLng);
var marker = new google.maps.Marker({
position: latLng,
title: propertyDetails.NAME,
icon: outIcon
});
// add an event listener for this marker
google.maps.event.addListener(marker , 'click', function() {
// assuming you have some content in a field called Field123
infowindow.setContent('<div class="infowindow"><div class="panel-image listing-img"><img style="max-height:115px;" width="100%" src="' + propertyDetails.THUMBNAIL + '"></div><p>' + propertyDetails.NAME + '</p></div>');
infowindow.open(map, this);
});
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
map.fitBounds(bounds);
try this way :
for (var i = startRow; i < AMdata.property.length; i++) {
var propertyDetails = AMdata.property[i];
var latLng = new google.maps.LatLng(propertyDetails.LATITUDE, propertyDetails.LONGITUDE);
bounds.extend(latLng);
var marker = new google.maps.Marker({
position: latLng,
title: propertyDetails.NAME,
icon: outIcon
});
// add an event listener for this marker
k = markers.push(marker);
google.maps.event.addListener(markers[k-1] , 'click', function(propertyDetail) {
// assuming you have some content in a field called Field123
infowindow.setContent('<div class="infowindow"><div class="panel-image listing-img"><img style="max-height:115px;" width="100%" src="' + propertyDetails.THUMBNAIL + '"></div><p>' + propertyDetails.NAME + '</p></div>');
infowindow.open(map, this);
});
}
var markerCluster = new MarkerClusterer(map, markers);
map.fitBounds(bounds);

How can i change the Marker color clicked previously to its original color

I am displaying markers on a Google map .
When i click on the marker , i am setting it to different color (blue)
like this
this.setIcon("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
This is my full code
var map;
var global_markers = [];
var markers = [[37.09024, -95.712891, 'trialhead0'], [-14.235004, -51.92528, 'trialhead1'], [-38.416097, -63.616672, 'trialhead2']];
var infowindow = new google.maps.InfoWindow({});
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
addMarker();
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var trailhead_name = markers[i][2];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + trailhead_name + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Trailhead name: " + trailhead_name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
this.setIcon("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
window.onload = initialize;
http://jsfiddle.net/ZLuTg/1008/
My question is that when i click on another Marker , how can i set the prevous marker which is in blue color to its original color
You already have an array of all your markers. Loop over them, resetting their icons.
Either do this for all the markers, then set the current one to blue. Or within the loop have an if statement checking if the one being looped over is the currently clicked one (I prefer the first option).
google.maps.event.addListener(global_markers[i], 'click', function() {
for (var j = 0; j < global_markers.length; j++) {
global_markers[j].setIcon("http://maps.google.com/mapfiles/ms/icons/red-dot.png");
}
this.setIcon("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
Your original marker is the default marker. To set it back to that call setIcon(null).
google.maps.event.addListener(global_markers[i], 'click', function () {
for (var j = 0; j < global_markers.length; j++) {
global_markers[j].setIcon(null);
}
this.setIcon("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
working fiddle
code snippet:
var map;
var global_markers = [];
var markers = [
[37.09024, -95.712891, 'trialhead0'],
[-14.235004, -51.92528, 'trialhead1'],
[-38.416097, -63.616672, 'trialhead2']
];
var infowindow = new google.maps.InfoWindow({});
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
addMarker();
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var trailhead_name = markers[i][2];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + trailhead_name + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Trailhead name: " + trailhead_name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
for (var j = 0; j < global_markers.length; j++) {
global_markers[j].setIcon(null);
}
this.setIcon("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
window.onload = initialize;
#map_canvas {
width: 600px;
height: 500px;
}
<script src="http://maps.google.com/maps/api/js"></script>
<div id="map_canvas"></div>

Google Maps Api - drawing routes from an array of points

I would like to connect 8 points on google map so that they shared line (road). I would like to click on the point cloud showed up with a description that point. The goal is to show the route the car point to point.
I have script to make map with points but I don't know how connect markers.
var MapPoints = '[{"address":{"address":"plac Grzybowski, Warszawa, Polska","lat":"52.2360592","lng":"21.002903599999968"},"title":"Warszawa"},{"address":{"address":"Jana Paw\u0142a II, Warszawa, Polska","lat":"52.2179967","lng":"21.222655600000053"},"title":"Wroc\u0142aw"},{"address":{"address":"Wawelska, Warszawa, Polska","lat":"52.2166692","lng":"20.993677599999955"},"title":"O\u015bwi\u0119cim"}]';
var MY_MAPTYPE_ID = 'custom_style';
function initialize() {
if (jQuery('#map').length > 0) {
var locations = jQuery.parseJSON(MapPoints);
window.map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
map: map
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i]['title']);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892)
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
var flightPath = responseArray.map(function (item) {
return new google.maps.LatLng(item.latitude, item.longitude);
});
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(12);
google.maps.event.removeListener(listener);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
to connect your markers with a google.maps.Polyline (as it looks like you are trying to do).
create an empty array: var flightPlanCoordinates = [];
push the coordinates of the markers (google.maps.LatLng objects) into the array of coordinates you use for the polyline: flightPlanCoordinates.push(marker.getPosition());
set the map option of the polyline: map:map (in the PolylineOptions object).
var flightPath = new google.maps.Polyline({
map: map,
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
working fiddle
working code snippet:
var MapPoints = '[{"address":{"address":"plac Grzybowski, Warszawa, Polska","lat":"52.2360592","lng":"21.002903599999968"},"title":"Warszawa"},{"address":{"address":"Jana Paw\u0142a II, Warszawa, Polska","lat":"52.2179967","lng":"21.222655600000053"},"title":"Wroc\u0142aw"},{"address":{"address":"Wawelska, Warszawa, Polska","lat":"52.2166692","lng":"20.993677599999955"},"title":"O\u015bwi\u0119cim"}]';
var MY_MAPTYPE_ID = 'custom_style';
function initialize() {
if (jQuery('#map').length > 0) {
var locations = jQuery.parseJSON(MapPoints);
window.map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
var infowindow = new google.maps.InfoWindow();
var flightPlanCoordinates = [];
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
map: map
});
flightPlanCoordinates.push(marker.getPosition());
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i]['title']);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
var flightPath = new google.maps.Polyline({
map: map,
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="map" style="border: 2px solid #3872ac;"></div>
to connect the points using the directions service (from the example you reference)
create an empty array: var flightPlanCoordinates = [];
push the coordinates of the markers (google.maps.LatLng objects) into the array of coordinates you use for the polyline: flightPlanCoordinates.push(marker.getPosition());
use that array to populate the start, end, and waypts arguments into the calcRoute function:
var start = flightPlanCoordinates[0];
var end = flightPlanCoordinates[flightPlanCoordinates.length - 1];
var waypts = [];
for (var i = 1; i < flightPlanCoordinates.length - 1; i++) {
waypts.push({
location: flightPlanCoordinates[i],
stopover: true
});
}
calcRoute(start, end, waypts);
change the calcRoute function to use those arguments:
function calcRoute(start, end, waypts) {
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
working fiddle
working code snippet:
var MapPoints = '[{"address":{"address":"plac Grzybowski, Warszawa, Polska","lat":"52.2360592","lng":"21.002903599999968"},"title":"Warszawa"},{"address":{"address":"Jana Paw\u0142a II, Warszawa, Polska","lat":"52.2179967","lng":"21.222655600000053"},"title":"Wroc\u0142aw"},{"address":{"address":"Wawelska, Warszawa, Polska","lat":"52.2166692","lng":"20.993677599999955"},"title":"O\u015bwi\u0119cim"}]';
var MY_MAPTYPE_ID = 'custom_style';
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
if (jQuery('#map').length > 0) {
var locations = jQuery.parseJSON(MapPoints);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
directionsDisplay.setMap(map);
var infowindow = new google.maps.InfoWindow();
var flightPlanCoordinates = [];
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
map: map
});
flightPlanCoordinates.push(marker.getPosition());
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i]['title']);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
// directions service configuration
var start = flightPlanCoordinates[0];
var end = flightPlanCoordinates[flightPlanCoordinates.length - 1];
var waypts = [];
for (var i = 1; i < flightPlanCoordinates.length - 1; i++) {
waypts.push({
location: flightPlanCoordinates[i],
stopover: true
});
}
calcRoute(start, end, waypts);
}
}
function calcRoute(start, end, waypts) {
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
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>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="map" style="border: 2px solid #3872ac;"></div>
<div id="directions_panel"></div>

Google Maps API v3 Point of Interest with Custom Icons

I have a page pulling in the schools, churches, and parks of my given area but I want to style the 3 POIs with 3 different icons. I searched Google and even all the docs but couldn't find the answer.
var map;
var infowindow;
function initialize() {
// Center of Map
var centerLatlng = new google.maps.LatLng(29.745376, -95.380125);
// Marker Icons Declaration
var icon = new google.maps.MarkerImage("smLinks-twitter.png", null, null, new google.maps.Point(41,47));
// Map Options
var myOptions = {
zoom: 16,
center: centerLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
icons: icon
};
// Draw the map
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Marker Icons Implementation
markers = new google.maps.Marker({
position: centerLatlng,
map: map,
title: 'Center of Map',
icon: icon
});
// Services: Places
var request = {
location: centerLatlng,
radius: 800,
types: ["school", "church", "park"]
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
} // function initialize()
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.setContent(place.name + '<br/>' + place.vicinity + '<br/><img src="' + place.icon + '">');
infowindow.open(map, this);
});
}
Please see my quick and dirty Demo. The idea is to use the place.types array to determine what kind of place you are trying to add to the map. I simplistically assigned a marker to the first item of this array (usually 2 or 3 items long), which may be something like:
["school", "establishment"]
In some cases, "university" comes before "school" so a "university" icon is used. You will want to refine the way you match types to icons, that is, give a priority for school or university? Perhaps iterate through the array looking for the right types. One place (general_contractor) is not in my list of icons, so the default pin marker is placed there. A "default" icon could be used if you checked if iconType in fact has or not the desired type. I'll leave these details to you =)
Here's the source I used for icons: https://sites.google.com/site/gmapsdevelopment/
function createMarker(place) {
var placeLoc = place.geometry.location;
var iconType = {};
iconType['school'] = "http://maps.google.com/mapfiles/kml/pal2/icon2.png";
iconType['church'] = "http://maps.google.com/mapfiles/kml/pal2/icon11.png";
iconType['park'] = "http://maps.google.com/mapfiles/kml/pal2/icon12.png";
iconType['university'] = "http://maps.google.com/mapfiles/kml/pal2/icon14.png";
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: iconType[place.types[0]]
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.setContent(place.name + '<br/>' + place.vicinity + '<br/><img src="' + place.icon + '">');
infowindow.open(map, this);
});
}
Alternatively, use a switch statement:
function createMarker(place) {
var placeLoc = place.geometry.location;
var iconUrl;
switch (place.types[0]) {
case 'school':
iconUrl = "http://maps.google.com/mapfiles/kml/pal2/icon2.png";
break;
case 'church':
iconUrl = "http://maps.google.com/mapfiles/kml/pal2/icon11.png";
break;
case 'park':
iconUrl = "http://maps.google.com/mapfiles/kml/pal2/icon12.png";
break;
case 'university':
iconUrl = "http://maps.google.com/mapfiles/kml/pal2/icon14.png";
break;
default:
iconUrl = "http://maps.google.com/mapfiles/kml/pal4/icon39.png";
}
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: iconUrl
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.setContent(place.name + '<br/>' + place.vicinity + '<br/><img src="' + place.icon + '">');
infowindow.open(map, this);
});
}