Google maps api cluster marker and custom info and icon - javascript

Im having a problem with custom icons. I have managed to get different infotext on the markers, i have managed to get the clusters to work, but when i add var icon1 and var icon2 and place them in the location array: "icon: icon2. All fails, is there a way to use both icon, infowindow and clustermarkers?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Marker Clustering</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 63.418719, lng: 10.3685516}
});
var icon1 = {
url: "https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png", // url
scaledSize: new google.maps.Size(50, 50), // size
};
var icon2 = {
url: "https://maps.google.com/mapfiles/kml/shapes/library_maps.png", // url
scaledSize: new google.maps.Size(50, 50), // size
};
var infoWin = new google.maps.InfoWindow();
var markers = locations.map(function(location, i) {
var marker = new google.maps.Marker({
position:location
});
google.maps.event.addListener(marker, 'click', function(evt) {
infoWin.setContent(location.info);
infoWin.open(map, marker);
})
return marker;
});
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
{lat: 63.131623, lng: 10.370243, info:"Test1", icon: icon1},
{lat: 62.432600, lng: 10.300243, info:"Test2", icon: icon2},
{lat: 62.330642, lng: 10.300243, info:"Test2", icon: icon1},
{lat: 63.530691, lng: 10.300243, info:"Test2", icon: icon2},
]
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzoVQ&callback=initMap">
</script>
</body>
</html>

To actually use the icon in the locations array, change your marker definition from:
var markers = locations.map(function(location, i) {
var marker = new google.maps.Marker({
position:location
});
google.maps.event.addListener(marker, 'click', function(evt) {
infoWin.setContent(location.info);
infoWin.open(map, marker);
})
return marker;
});
To:
var markers = locations.map(function(location, i) {
var marker = new google.maps.Marker({
position: location,
icon: location.icon // <--------------------------------add this
});
google.maps.event.addListener(marker, 'click', function(evt) {
infoWin.setContent(location.info);
infoWin.open(map, marker);
})
return marker;
});
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {
lat: 63.418719,
lng: 10.3685516
}
});
var infoWin = new google.maps.InfoWindow();
var markers = locations.map(function(location, i) {
var marker = new google.maps.Marker({
position: location,
icon: location.icon
});
google.maps.event.addListener(marker, 'click', function(evt) {
infoWin.setContent(location.info);
infoWin.open(map, marker);
})
return marker;
});
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
var icon1 = {
url: "https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png", // url
scaledSize: new google.maps.Size(50, 50), // size
};
var icon2 = {
url: "https://maps.google.com/mapfiles/kml/shapes/library_maps.png", // url
scaledSize: new google.maps.Size(50, 50), // size
};
var locations = [{
lat: 63.131623,
lng: 10.370243,
info: "Test1",
icon: icon1
}, {
lat: 62.432600,
lng: 10.300243,
info: "Test2",
icon: icon2
}, {
lat: 62.330642,
lng: 10.300243,
info: "Test2",
icon: icon1
}, {
lat: 63.530691,
lng: 10.300243,
info: "Test2",
icon: icon2
}, ]
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&ext=.js"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<div id="map"></div>

Related

When I click a marker on Google map it should open multiple markers, but the marker that has been clicked should also appear

I have written code for Google Maps API where when I click a marker multiple markers should appear, but the marker that has been clicked should also appear. Means the page should not refresh. Please help me. Here is my code where if you click on the marker multiple markers will appear, but the marker disappears.
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap() {
var uluru = {lat: 25.2138, lng: 75.8648};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Hello World!',
map: map
});
marker.addListener('click', function() {
clicktoOpenMAp();
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
}
function clicktoOpenMAp() { var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
map.setTilt(50);
var markers = [
['chittorgarh', 24.8887, 74.6269],
['morak', 24.7265, 75.9739],
['mangrol', 25.3362, 76.5112]
];
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
map.fitBounds(bounds);
}
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(8);
google.maps.event.removeListener(boundsListener);
});
}
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key='YourGoogleApiBecauseicantsharemine'&callback=initMap"></script>
</body>
</html>
Please use your Google API key, because I can't share mine.
Ok, this is how I fixed it:
function initMap() {
var uluru = {
lat: 25.2138,
lng: 75.8648
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Hello World!',
map: map
});
marker.addListener('click', function() {
clicktoOpenMAp();
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
function clicktoOpenMAp() {
// var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// map = new google.maps.Map(document.getElementById("map"), mapOptions);
map.mapTypeId = "roadmap";
map.setTilt(50);
var markers = [
['chittorgarh', 24.8887, 74.6269],
['morak', 24.7265, 75.9739],
['mangrol', 25.3362, 76.5112]
];
for (i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
map.fitBounds(bounds);
}
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(8);
google.maps.event.removeListener(boundsListener);
});
}
}
You were "creating" another map everytime you clicked in the marker (I commented the line so you know), then you need to put the Function clicktoOpenMap inside initmap.
Note: I also added async defer to the script where you call the api
<script
src="https://maps.googleapis.com/maps/api/js?key='YourGoogleApiBecauseicantsharemine'&callback=initMap" async defer></script>
You can hide the markers with
markers[i].setMap(null);
and to erase them
var markers = [];

Labelling a marker on a Google Cluster Maps

With the help of another StackOverflow post I've got a map working which makes the markers into clickable links.
I also need the markers to have a label of some kind so the user knows where they'll link to (right now, they're just blank pins) but I'm not sure how to modify this code to build that function in.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {lat: 53.618939, lng: -2.1602328}
});
var locations = [
["http://www.google.com", {lat: 53.618939, lng: -2.1601132}],
["http://www.google.com", {lat: 53.61953, lng: -2.1623746}],
["http://www.google.com", {lat: 53.6178993, lng: -2.1601596}],
["http://www.google.com", {lat: 53.5369545, lng: -1.9941523}],
["http://www.google.com", {lat: 53.5380496, lng: -1.9974085}],];
var markers = locations.map(function(location) {
var marker = new google.maps.Marker({
map: map,
position: location[1],
url: location[0] //Will be different for each marker
});
google.maps.event.addListener(marker, 'click', function(){
window.location.href = this.url;
});
return marker;
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
To label each marker with a unique letter (at least for up to 26 markers), you can follow this example in the documentation
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
var markers = locations.map(function(location) {
var marker = new google.maps.Marker({
map: map,
position: location[1],
label: labels[labelIndex++ % labels.length],
url: location[0] //Will be different for each marker
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
return marker;
});
proof of concept fiddle
code snippet:
// In the following example, markers appear when the user clicks on the map.
// Each marker is labeled with a single alphabetical character.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {
lat: 53.618939,
lng: -2.1602328
}
});
var locations = [
["http://www.google.com", {lat: 53.618939,lng: -2.1601132}],
["http://www.google.com", {lat: 53.61953,lng: -2.1623746}],
["http://www.google.com", {lat: 53.6178993,lng: -2.1601596}],
["http://www.google.com", {lat: 53.5369545,lng: -1.9941523}],
["http://www.google.com", {lat: 53.5380496,lng: -1.9974085}],
];
var markers = locations.map(function(location) {
var marker = new google.maps.Marker({
map: map,
position: location[1],
label: labels[labelIndex++ % labels.length],
url: location[0] //Will be different for each marker
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
return marker;
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerclustererplus/src/markerclusterer.js"></script>
<div id="map"></div>

Show nearest elements on google map

I am creating a project using google map. My project contains hospital address ( in longitude and latitude) to be stored in database. But I want to show nearest hospital from my current location. And I am unable to figure out how to do it. Please help me with best algorithm and with some code.
Following code is used just to display all hospital address in map now I want is how to show only 3 nearest hospital from my current positiom.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
for (var i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var image = "img/iconHospital.png";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
title: data.district,
animation: animationType
});
}
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
See this example at. I adapted your code accordingly.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: nepalLocation,
radius: 50000,
type: ['hospital']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
if (i == 2) {
break;
}
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>

How can I show text when clicking on a Google Maps API marker?

How can I set a text when I click on the icon marker from google map?
The request is: when I click on a icon the text should appear and on I click on other icon only the selected icon should have text
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {
lat: 45.9356343,
lng: 25.9017273
}
});
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
icon: "/resources/service-points.png",
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
var locations = [{
lat: 44.426049,
lng: 26.047637
},
{
lat: 44.428430,
lng: 26.140104
},
{
lat: 44.487002,
lng: 26.078824
},
{
lat: 44.431288,
lng: 26.110165
}
]
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<body>
<div id="map"></div>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
</body>
You should use the InfoWindow object from Google :
*
https://developers.google.com/maps/documentation/javascript/infowindows?hl=fr
The code looks like this, create your object and then add a listener to your marker so it can launch the display of your window :)
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: uluru,
map: map,
title: 'Uluru (Ayers Rock)'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
you could use an info window
var contentString = 'my text for this marker'
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
icon: "/resources/service-points.png",
title: 'my marker'
});
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
here you can find a google sample https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple

Plotting two objects addresses on map.how to set two different design balloons for two objects?

<script>
function drawMap(){
var balloon = new google.maps.InfoWindow();
var mapOptions = {
center: coords[0],
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
con = con.replace(/[,;]$/,'');
var mystring =con;
var splits = mystring.split(",");
type = type.replace(/[,;]$/,'');
var mystring1 =type;
var splits1 = mystring1.split(",");
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
for(var i = 0; i < coords.length; ++i){
var marker = new google.maps.Marker({map: map, position: coords[i], title:splits1[i]+'-'+splits[i], zIndex:i});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
var index = this.zIndex;
balloon.setContent('<b>'+splits1[i]+'</b><br/>'+splits[i]);
balloon.open(map, marker);
}
})(marker, i));
markers.push(marker);
}
}
geocodeClientSide();
</script>
In Above code Split1[i] output returns as either "account" or "lead" .
I want to keep different design images for plotting account and lead .
Currently i am getting red color balloon by default ?
How can i do that ?
Thanks in advance
Asmentioned in google api In new google.maps.Marker().
please check this example. Here we are using two icons, 1 dotted black, and other brown.
var map;
var locations = [{
position: {
lat: -25.363,
lng: 131.044
},
icon: 'http://icons.iconarchive.com/icons/icons8/ios7/256/Maps-Location-icon.png',
}, {
position: {
lat: -28.363,
lng: 135.044,
},
icon: 'http://icons.iconarchive.com/icons/graphicloads/100-flat/256/location-icon.png',
}];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 4,
center: locations[0].position
});
for (var index in locations) {
var image = new google.maps.MarkerImage(
locations[index]['icon'],
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(20, 20));
var marker = new google.maps.Marker({
position: locations[index].position,
map: map ,
icon: image,
});
}
}
$(document).ready(function() {
initMap();
});
#map {
width: 300px;
height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Categories

Resources