Base on this http://jsfiddle.net/kaiser/wzcst/light/ example, but the marker in circle is not accurate, when the marker is outside circle and near to circle it is consider inside the circle which is not wanted.
Is there any other idea?
code snippet (from linked fiddle):
window.onload = function init() {
var
contentCenter = '<span class="infowin">Center Marker (draggable)</span>',
contentA = '<span class="infowin">Marker A (draggable)</span>',
contentB = '<span class="infowin">Marker B (draggable)</span>';
var
latLngCenter = new google.maps.LatLng(37.081476, -94.510574),
latLngCMarker = new google.maps.LatLng(37.0814, -94.5105),
latLngA = new google.maps.LatLng(37.2, -94.1),
latLngB = new google.maps.LatLng(38, -93),
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: latLngCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}),
markerCenter = new google.maps.Marker({
position: latLngCMarker,
title: 'Location',
map: map,
draggable: true
}),
infoCenter = new google.maps.InfoWindow({
content: contentCenter
}),
markerA = new google.maps.Marker({
position: latLngA,
title: 'Location',
map: map,
draggable: true
}),
infoA = new google.maps.InfoWindow({
content: contentA
}),
markerB = new google.maps.Marker({
position: latLngB,
title: 'Location',
map: map,
draggable: true
}),
infoB = new google.maps.InfoWindow({
content: contentB
})
// exemplary setup:
// Assumes that your map is signed to the var "map"
// Also assumes that your marker is named "marker"
,
circle = new google.maps.Circle({
map: map,
clickable: false,
// metres
radius: 100000,
fillColor: '#fff',
fillOpacity: .6,
strokeColor: '#313131',
strokeOpacity: .4,
strokeWeight: .8
});
// attach circle to marker
circle.bindTo('center', markerCenter, 'position');
var
// get the Bounds of the circle
bounds = circle.getBounds()
// Note spans
,
noteA = jQuery('.bool#a'),
noteB = jQuery('.bool#b');
noteA.text(bounds.contains(latLngA));
noteB.text(bounds.contains(latLngB));
// get some latLng object and Question if it's contained in the circle:
google.maps.event.addListener(markerCenter, 'dragend', function() {
latLngCenter = new google.maps.LatLng(markerCenter.position.lat(), markerCenter.position.lng());
bounds = circle.getBounds();
noteA.text(bounds.contains(latLngA));
noteB.text(bounds.contains(latLngB));
});
google.maps.event.addListener(markerA, 'dragend', function() {
latLngA = new google.maps.LatLng(markerA.position.lat(), markerA.position.lng());
noteA.text(bounds.contains(latLngA));
});
google.maps.event.addListener(markerB, 'dragend', function() {
latLngB = new google.maps.LatLng(markerB.position.lat(), markerB.position.lng());
noteB.text(bounds.contains(latLngB));
});
google.maps.event.addListener(markerCenter, 'click', function() {
infoCenter.open(map, markerCenter);
});
google.maps.event.addListener(markerA, 'click', function() {
infoA.open(map, markerA);
});
google.maps.event.addListener(markerB, 'click', function() {
infoB.open(map, markerB);
});
google.maps.event.addListener(markerCenter, 'drag', function() {
infoCenter.close();
noteA.html("draggin…");
noteB.html("draggin…");
});
google.maps.event.addListener(markerA, 'drag', function() {
infoA.close();
noteA.html("draggin…");
});
google.maps.event.addListener(markerB, 'drag', function() {
infoB.close();
noteB.html("draggin…");
});
};
body {
margin: 0;
padding: 0
}
html,
body,
#map {
height: 100%;
font-family: Arial, sans-serif;
font-size: .9em;
color: #fff;
}
#note {
text-align: center;
padding: .3em;
10px;
background: #009ee0;
}
.bool {
font-style: italic;
color: #313131;
}
.info {
display: inline-block;
width: 40%;
text-align: center;
}
.infowin {
color: #313131;
}
#title,
.bool {
font-weight: bold;
}
<script src="http://maps.googleapis.com/maps/api/js"></script>
<div id="note"><span id="title">»Inside the circle?«</span>
<hr /><span class="info">Marker <strong>A</strong>: <span id="a" class="bool"></span></span>←♦→ <span class="info">Marker <strong>B</strong>: <span id="b" class="bool"></span></span>
</div>
<div id="map">test</div>
A google.maps.LatLngBounds is a rectangle. You need a polygon "contains" function. For a circle this can be reduced to testing whether the point is less than the radius away from the center.
Example
code snippet:
window.onload = function init() {
var
contentCenter = '<span class="infowin">Center Marker (draggable)</span>',
contentA = '<span class="infowin">Marker A (draggable)</span>',
contentB = '<span class="infowin">Marker B (draggable)</span>';
var
latLngCenter = new google.maps.LatLng(37.081476, -94.510574),
latLngCMarker = new google.maps.LatLng(37.0814, -94.5105),
latLngA = new google.maps.LatLng(37.2, -94.1),
latLngB = new google.maps.LatLng(38, -93),
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: latLngCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}),
markerCenter = new google.maps.Marker({
position: latLngCMarker,
title: 'Center of Circle',
map: map,
draggable: true
}),
infoCenter = new google.maps.InfoWindow({
content: contentCenter
}),
markerA = new google.maps.Marker({
position: latLngA,
title: 'A',
map: map,
label: "A",
draggable: true
}),
infoA = new google.maps.InfoWindow({
content: contentA
}),
markerB = new google.maps.Marker({
position: latLngB,
title: 'B',
map: map,
label: "B",
draggable: true
}),
infoB = new google.maps.InfoWindow({
content: contentB
})
// exemplary setup:
// Assumes that your map is signed to the var "map"
// Also assumes that your marker is named "marker"
,
circle = new google.maps.Circle({
map: map,
clickable: false,
// metres
radius: 100000,
fillColor: '#fff',
fillOpacity: .6,
strokeColor: '#313131',
strokeOpacity: .4,
strokeWeight: .8
});
// attach circle to marker
circle.bindTo('center', markerCenter, 'position');
var
// get the Bounds of the circle
bounds = circle.getBounds()
// Note spans
,
noteA = jQuery('.bool#a'),
noteB = jQuery('.bool#b');
noteA.text((100000 > google.maps.geometry.spherical.computeDistanceBetween(markerA.getPosition(), markerCenter.getPosition())));
noteB.text((100000 > google.maps.geometry.spherical.computeDistanceBetween(markerB.getPosition(), markerCenter.getPosition())));
// get some latLng object and Question if it's contained in the circle:
google.maps.event.addListener(markerCenter, 'dragend', function() {
latLngCenter = markerCenter.position;
noteA.text((100000 > google.maps.geometry.spherical.computeDistanceBetween(markerA.getPosition(), markerCenter.getPosition())));
noteB.text((100000 > google.maps.geometry.spherical.computeDistanceBetween(markerB.getPosition(), markerCenter.getPosition())));
});
google.maps.event.addListener(markerA, 'dragend', function() {
latLngA = markerA.position;
noteA.text((100000 > google.maps.geometry.spherical.computeDistanceBetween(markerA.getPosition(), markerCenter.getPosition())));
});
google.maps.event.addListener(markerB, 'dragend', function() {
latLngB = markerB.position;
noteB.text((100000 > google.maps.geometry.spherical.computeDistanceBetween(markerB.getPosition(), markerCenter.getPosition())));
});
google.maps.event.addListener(markerCenter, 'click', function() {
infoCenter.open(map, markerCenter);
});
google.maps.event.addListener(markerA, 'click', function() {
infoA.open(map, markerA);
});
google.maps.event.addListener(markerB, 'click', function() {
infoB.open(map, markerB);
});
google.maps.event.addListener(markerCenter, 'drag', function() {
infoCenter.close();
noteA.html("draggin…");
noteB.html("draggin…");
});
google.maps.event.addListener(markerA, 'drag', function() {
infoA.close();
noteA.html("draggin…");
});
google.maps.event.addListener(markerB, 'drag', function() {
infoB.close();
noteB.html("draggin…");
});
};
body {
margin: 0;
padding: 0
}
html,
body,
#map {
height: 100%;
font-family: Arial, sans-serif;
font-size: .9em;
color: #fff;
}
#note {
text-align: center;
padding: .3em;
10px;
background: #009ee0;
}
.bool {
font-style: italic;
color: #313131;
}
.info {
display: inline-block;
width: 40%;
text-align: center;
}
.infowin {
color: #313131;
}
#title,
.bool {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="note"><span id="title">»Inside the circle?«</span>
<hr /><span class="info">Marker <strong>A</strong>: <span id="a" class="bool"></span></span>←♦→ <span class="info">Marker <strong>B</strong>: <span id="b" class="bool"></span></span>
</div>
<div id="map">test</div>
Related
I can't seem to find any documentation about updating the path of an icon (marker) in the Google Maps API. In this particular example I'm trying to change the fillOpacity of the icon from 0 to 1.
var myIcon = {
path: google.maps.SymbolPath.CIRCLE,
scale: 5,
fillColor: "#ff00ff",
fillOpacity: 0,
strokeColor: "#ff00ff",
strokeWeight: 2
};
var marker = new google.maps.Marker({
position: position,
icon: myIcon,
map: map,
title: 'My Marker>'
});
marker.addListener('click', function() {
this.setOptions({icon:{fillOpacity: 0.5}}); // Not working
this.setIcon({fillOpacity: 0.2}); // Not working either
});
The "icon" is an anonymous object. You need to set the whole object again:
marker.addListener('click', function() {
myIcon.fillOpacity = 0.5;
this.setIcon(myIcon);
});
or:
marker.addListener('click', function() {
myIcon.fillOpacity = 0.5;
this.setOptions({
icon: myIcon
});
});
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: -25.363882,
lng: 131.044922
}
});
var myIcon = {
path: google.maps.SymbolPath.CIRCLE,
scale: 5,
fillColor: "#ff00ff",
fillOpacity: 0,
strokeColor: "#ff00ff",
strokeWeight: 2
};
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: myIcon,
map: map,
title: 'My Marker>'
});
marker.addListener('click', function() {
myIcon.fillOpacity = 0.5;
this.setIcon(myIcon);
});
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
I am working on this demo. Why am I getting this error:
overlay.getBounds is not a function
while trying to get bounds of drawn rectangle on the map?
var rectangle;
var map;
var drawingManager;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 44.5452,
lng: -78.5389
},
zoom: 9
});
drawingManager = new google.maps.drawing.DrawingManager();
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(overlay) {
rectangle = overlay;
drawingManager.setOptions({
drawingMode: null,
drawingControl: false
});
var bounds = overlay.getBounds();
var start = bounds.getNorthEast();
var end = bounds.getSouthWest();
console.log( start);
});
}
google.maps.event.addDomListener(window, 'load', initMap);
function drawRec() {
//Setting options for the Drawing Tool. In our case, enabling Polygon shape.
if (!!rectangle && !!rectangle.overlay && !!rectangle.overlay.setMap) {
rectangle.overlay.setMap(null);
}
drawingManager.setOptions({
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControl: false,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [google.maps.drawing.OverlayType.RECTANGLE]
},
rectangleOptions: {
strokeColor: '#6c6c6c',
strokeWeight: 3.5,
fillColor: '#926239',
fillOpacity: 0.6,
editable: true,
draggable: true
}
});
drawingManager.setMap(map);
}
html,
body,
#map {
height: 100%;
height: 100%;
margin: 0;
padding: 0;
}
<button onclick="drawRec();">Draw Rectangle</button>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing"></script>
You get the error: "overlay.getBounds is not a function", because overlay.getBounds() is not a function. overlay is not a google.maps.Rectangle, but it has an overlay property which is.
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(overlay) {
rectangle = overlay;
drawingManager.setOptions({
drawingMode: null,
drawingControl: false
});
var bounds = overlay.overlay.getBounds();
var start = bounds.getNorthEast();
var end = bounds.getSouthWest();
console.log(start.toUrlValue(6));
});
updated fiddle
code snippet:
var rectangle;
var map;
var drawingManager;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 44.5452,
lng: -78.5389
},
zoom: 9
});
drawingManager = new google.maps.drawing.DrawingManager();
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(overlay) {
rectangle = overlay;
drawingManager.setOptions({
drawingMode: null,
drawingControl: false
});
var bounds = overlay.overlay.getBounds();
var start = bounds.getNorthEast();
var end = bounds.getSouthWest();
console.log(bounds.toUrlValue(6));
});
}
google.maps.event.addDomListener(window, 'load', initMap);
function drawRec() {
//Setting options for the Drawing Tool. In our case, enabling Polygon shape.
if (!!rectangle && !!rectangle.overlay && !!rectangle.overlay.setMap) {
rectangle.overlay.setMap(null);
}
drawingManager.setOptions({
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControl: false,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [google.maps.drawing.OverlayType.RECTANGLE]
},
rectangleOptions: {
strokeColor: '#6c6c6c',
strokeWeight: 3.5,
fillColor: '#926239',
fillOpacity: 0.6,
editable: true,
draggable: true
}
});
drawingManager.setMap(map);
}
html,
body,
#map {
height: 100%;
height: 100%;
margin: 0;
padding: 0;
}
<button onclick="drawRec();">Draw Rectangle</button>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing"></script>
Check the documentation:
https://developers.google.com/maps/documentation/javascript/drawinglayer#drawing_events
The overlay event in your event listener has two properties:
overlay
type
So you'd need to change your code to something like this:
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(overlayEvent) {
rectangle = overlayEvent.overlay;
drawingManager.setOptions({
drawingMode: null,
drawingControl: false
});
var bounds = rectangle.getBounds();
var start = bounds.getNorthEast();
var end = bounds.getSouthWest();
});
I have a list of places in a text box in Google maps. When a person clicks on one of the places in the text box, I want the corresponding marker of that location in Google Maps to bounce. Any ideas on how I can make this work? Right now I am only able to make the marker bounce when I click on the marker itself.
Here is my code:
var Points = [ {
name: 'Duomo-Cathedral',
lat: 43.7732,
long: 11.2560,
url: 'http://www.google.com'
}, {
name: 'Orsanmichele-Church',
lat: 43.770947,
long: 11.254981,
url: 'http://www.google.com'
}, {
name: 'Ponte Vecchio-Old Bridge',
lat: 43.768350,
long: 11.253323,
url: 'http://www.google.com'
}, {
name: 'Galleria delgi Uffizzi-Art Gallery',
lat: 43.768657,
long: 11.255737,
url: 'http://www.google.com'
}, {
name: 'Santa Croce-Church',
lat: 43.768816,
long: 11.262394,
add1: 'Piazza Santa Croce, 16',
add2: ' Florence, Italy 50122',
phone: '+39 055 246 6105',
url: 'https://www.santacroceopera.it/'
}, {
name: 'Palazzo Vecchio-TownHall',
lat: 43.769670,
long: 11.256075,
url: 'https://www.google.com'
}, {
name: 'Piazza della Signoria-OpenSquare',
lat: 43.769725,
long: 11.255474,
url: 'http://www.google.com/'
}, {
name: 'Santa Maria Novella-Church',
lat: 43.774502,
long: 11.249466,
url: 'https://www.google.com'
}, {
name: 'Santa Maria Novella-TrainStation',
lat: 43.776261,
long: 11.248737,
url: 'https://www.google.com'
}, {
name: 'San Lorenzo- ChurchMarket',
lat: 43.774858,
long: 11.254584,
url: 'http://www.google.com'
}
];
var markersArray = ko.observableArray([]);
Points.forEach(populateMarkersArray);
function populateMarkersArray(element) { //, index, array
markersArray.push(element);
}
// Set up a google map
var mapOptions = {
center: { lat: 43.771341,lng: 11.256875},
zoom: 16
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
function initialize() {
Points.forEach(loadMarkers);
var infowindow0 = new google.maps.InfoWindow();
var marker0 = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(function() {
infowindow0.close();
marker0.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
marker0.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker0.setPosition(place.geometry.location);
marker0.setVisible(true);
infowindow0.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow0.open(map, marker0);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function loadMarkers(element) { //, index, array
var myLatlng = new google.maps.LatLng(element.lat,element.long);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: element.name
});
loadInfoWindow(element, marker);
}
function loadInfoWindow(element, marker) {
var contentString = '<div class="strong">' + element.name + '</div><div>' + element.add1 + '</div><div>' + element.add2 + '</div><div>'+ element.phone + '</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
toggleBounce(marker);
});
}
function toggleBounce(marker) {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
function viewModel() {
}
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Marker Animations</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0; }
#map-canvas { height: 100% }
.place-list {
display: inline-block;
width: 250px;
max-height: 70%;
float: right;
position: absolute;
top: 40px;
right: 6px;
z-index: 5;
overflow-y: auto;
background-color: white;
border: 2px solid grey;
opacity: 0.8;
list-style-type: none;
padding: 20px;
margin: auto;
font-weight: bolder;
border-radius: 25px;
}
</style>
</head>
<body>
<ul class="place-list" data-bind="foreach: Points" >
<li data-bind="text: name, click: $parent.marker" ></li>
</ul>
<div id="map-canvas"></div>
<script type="text/javascript" src="https://maps.googleapis.Com/maps/api/js?key=AIzaSyCPgww-LhtxoQqq2zLI1_gOU1L2XayS-rE"> </script>
<script src="js/lib/knockout-3.2.0.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Thanks for your help,
Max
One of the ways to do it is to use Knockout.js data-binding. In particular, you can use foreach binding to display all your items as a list and apply functions to each of them. Then use click binding to execute functions attached to list items when a user clicks on it. An example of how to use it for list view of places in Google Maps with search function:
HTML:
<h4>Places</h4>
<input type="text" id="my-Input" data-bind="textInput: filter" placeholder="Search for places..">
<div class="scroll" id="my-UL">
<ul data-bind="foreach: visiblePlaces">
<li>
<input data-bind="value: title, click: $parent.zoomToPlace, text: address" type="button" class="btn btn-small btn-link" id="zoomTo">
</li>
</ul>
</div>
JS:
/ ViewModel - provides list view of places, on click zooms map, shows the marker, infowindow, etc.
function viewModel() {
var self = this;
self.places = ko.observableArray(locations);
self.address = ko.observable();
self.title = ko.observable();
self.id = ko.observable();
this.filter = ko.observable();
this.visiblePlaces = ko.computed(function() {
return this.places().filter(function(place) {
if (!self.filter() || place.title.toLowerCase().indexOf(self.filter().toLowerCase()) !== -1)
return place;
});
}, this);
//Zooms to a selected marker and open infowindow
self.zoomToPlace = function() {
// Initialize the geocoder.
var geocoder = new google.maps.Geocoder();
// Get the place.
var address = this.address;
var id = this.id;
// Geocode the address/area entered to get the center. Then, center the map on it and zoom in
geocoder.geocode({
address: address,
}, function(results, status) {
map.setCenter(results[0].geometry.location);
map.setZoom(15);
google.maps.event.trigger(markers[id], 'click');
});
};
}
var vm = new viewModel();
ko.applyBindings(vm);
This will produce a list of places from an array (styles and array aren't shown in the code) and the corresponding marker will open an infowindow and bounce.
For full code, you can look it in my repo: https://github.com/DmitryGrechko/Neighborhood_Map
I've looked through a lot of the similar questions on here, but have not found anything that will answer my question. I am new to JS and GoogleMaps API v3, and have successfully followed their tutorials to get this far. However, I'd like to have an infowindow with custom content appear based on which marker is clicked, and I cannot figure out how to do this. I'd also like to have this be possible with around 100 markers, so I'd like to know the best way to do this as well without things getting too messy. To be clear, there are 3 types of icons, but there will eventually be many markers associated with each icon, so I will need content linked to each "feature". Hopefully I've got a good start here and am not way off base. I've included the code for the page. Thank you so much in advance for any help anyone can provide.
<!DOCTYPE html>
<html>
<head>
<style>
#map_canvas {
width: 800px;
height: 500px;
background-color:#CCC;
}
#legend {
font-family: Arial, sans-serif;
background: #fff;
padding: 10px;
margin: 10px;
border: 3px solid #000;
}
#legend img {
vertical-align: middle;
}
</style>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(33.137551,-0.703125),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(map_canvas, map_options);
map.set('styles', [
{
featureType: 'road',
elementType: 'geometry',
stylers: [
{ color: '#888888' },
{ weight: 1.0 }
]
}, {
featureType: 'landscape',
elementType: 'geometry.fill',
stylers: [
{ hue: '#008f11' },
{ gamma: 1.0 },
{ saturation: 0 },
{ lightness: -10 }
]
}, {
featureType: 'water',
elementType: 'geometry.fill',
stylers: [
{ hue: '#054d8fd' },
{ gamma: 1.0 },
{ saturation: 0 },
{ lightness: -10 }
]
}, {
featureType: 'poi',
elementType: 'geometry',
stylers: [
{ visibility: 'off' }
]
}
]);
var iconBase = 'http://i1318.photobucket.com/albums/t658/greatergoodorg/';
var icons = {
people: {
name: 'People',
icon: iconBase + 'people_zps26d13009.png',
shadow: iconBase + 'shadow-people_zps4b39eced.png'
},
pets: {
name: 'Pets',
icon: iconBase + 'pets_zps15f549f2.png',
shadow: iconBase + 'shadow-pets_zps361068aa.png'
},
planet: {
name: 'Planet',
icon: iconBase + 'planet_zps2a8572ce.png',
shadow: iconBase + 'shadow-planet_zps9912e26b.png',
}
};
var data = ["This is the first one", "This is the second one", "This is the third one"];
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
shadow: {
url: icons[feature.type].shadow,
anchor: new google.maps.Point(21, 32)
},
animation: google.maps.Animation.DROP,
map: map
});
/*...
google.maps.event.addListener(marker, "click", function () {
infowindow.open(map,marker);
});
...*/
/*...
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(8);
map.setCenter(marker.getPosition());
});
...*/
}
var features = [
{
position: new google.maps.LatLng(33.137551,-0.703125),
type: 'planet'
},
{
position: new google.maps.LatLng(44.234234,-0.232233),
type: 'pets'
},
{
position: new google.maps.LatLng(54.234234,-0.032233),
type: 'people'
}
];
for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}
var legend = document.getElementById('legend');
for (var key in icons) {
var type = icons[key];
var name = type.name;
var icon = type.icon;
var div = document.createElement('div');
div.innerHTML = '<img src="' + icon + '"> ' + name;
legend.appendChild(div);
}
map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(
document.getElementById('legend'));
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
<div id="legend"><strong>Project Types</strong></div>
</body>
</html>
This will open an infowindow and display the "type" string in it
var infowindow = new google.maps.InfoWindow();
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
shadow: {
url: icons[feature.type].shadow,
anchor: new google.maps.Point(21, 32)
},
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(feature.type);
infowindow.open(map,marker);
});
}
Refer from this source google map drawing tools, how to deleted all the drawing shape by one click button?
code snippet:
var drawingManager;
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color) {
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set('strokeColor', color);
} else {
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color) {
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(22.344, 114.048),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);
#map, html, body {
padding: 0;
margin: 0;
height: 100%;
}
#panel {
width: 200px;
font-family: Arial, sans-serif;
font-size: 13px;
float: right;
margin: 10px;
}
#color-palette {
clear: both;
}
.color-button {
width: 14px;
height: 14px;
font-size: 0;
margin: 2px;
float: left;
cursor: pointer;
}
#delete-button {
margin-top: 5px;
}
<script src="http://maps.google.com/maps/api/js?libraries=drawing"></script>
<div id="panel">
<div id="color-palette"></div>
<div>
<button id="delete-button">Delete Selected Shape</button>
</div>
</div>
<div id="map"></div>
If you want to delete (or do anything with) all the objects on the map, you need to keep references to them that you can use.
When a shape is created, push it into an array (needs to be global to be used in a button click handler).
When the "delete all" button is clicked, iterate through that array, calling .setMap(null) on each of the objects.
Example
Push the overlay onto an array (all_overlays):
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
all_overlays.push(e);
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
Delete all shapes:
function deleteAllShape() {
for (var i=0; i < all_overlays.length; i++)
{
all_overlays[i].overlay.setMap(null);
}
all_overlays = [];
}
Code snippet:
var drawingManager;
var all_overlays = [];
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function deleteAllShape() {
for (var i = 0; i < all_overlays.length; i++) {
all_overlays[i].overlay.setMap(null);
}
all_overlays = [];
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color) {
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set('strokeColor', color);
} else {
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color) {
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(22.344, 114.048),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
all_overlays.push(e);
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
google.maps.event.addDomListener(document.getElementById('delete-all-button'), 'click', deleteAllShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);
#map,
html,
body {
padding: 0;
margin: 0;
height: 100%;
}
#panel {
width: 200px;
font-family: Arial, sans-serif;
font-size: 13px;
float: right;
margin: 10px;
}
#color-palette {
clear: both;
}
.color-button {
width: 14px;
height: 14px;
font-size: 0;
margin: 2px;
float: left;
cursor: pointer;
}
#delete-button {
margin-top: 5px;
}
<script src="http://maps.google.com/maps/api/js?libraries=drawing&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="panel">
<div id="color-palette"></div>
<div>
<button id="delete-button">Delete Selected Shape</button>
<button id="delete-all-button">Delete All Shapes</button>
</div>
</div>
<div id="map"></div>