Google Maps MarkerClusterer not showing any default images - google-maps

I'm adding javascript code snippet to my Wordpress post (Hosted by a 3rd Party). I managed to create an array of Markers, and had them added to the MarkerClusterer and Map. The cluster shows up but as a broken image link and a number.
How do I access the MarkerClusterer default images? I followed the instructions from https://github.com/googlemaps/js-markerclusterer/blob/main/README.md
I'm not sure how to use npm with the 3rd party hosting. I don't use a database with my website. I'm calling src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js" to import MarkerClusterer
<div id="gmap" style="width:100%;height:400px;"></div>
<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"</script>
var mymap;
var markers = [];
function initMap() {
var centerpoint = { lat: 38.5, lng: -98 }; //centered around Kansas
mymap = new google.maps.Map(document.getElementById('gmap'), {
zoom: 4,
center: centerpoint
});
}
/** fetching a cvs file on the server side with a list of locations */
fetch("https://mywebsite.com/wp-content/uploads/2022/03/stores.csv")
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.text().then(function(data) {
count = 0;
console.log("fetch called successfully");
initMap();
processCSV(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
function processCSV(allData){
const rows = allData.split('\n');
var storename, storephone, storeaddress, storelat, storelng;
for(let i=0; i<rows.length; i++){
var line = rows[i];
storename = line.split(",")[1];
storephone = line.split(",")[3];
storeaddress = String(line.split(",")[2]);
storeaddress = replaceAll(storeaddress, "^", ",");
storelat = line.split(",")[4];
storelng = line.split(",")[5];
createMarker(storename, storephone, storeaddress, storelat, storelng);
}
createCluster();
}
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
function createCluster(){
var mcluster =new MarkerClusterer( mymap , markers);
}
function createMarker(name, phone, address, latstr, lngstr) {
var contentString = "<b>" + name + "</b><br><br><i>" + phone + "</i><br><br>" + address;
var latLng = { lat: Number(latstr) , lng: Number(lngstr)};
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var marker = new google.maps.Marker({
position: latLng,
map: mymap,
title: name
});
markers.push(marker);
console.log("added marker to map" + name);
marker.addListener("click", () => {
infowindow.open({
anchor: marker,
map: mymap,
shouldFocus: false,
});
});
}
<script src="https://maps.googleapis.com/maps/api/js?key=<PRIVATEKEY>;callback=initMap"></script>

The version of MarkerClusterer you are using doesn't require ClusterIcons (unless you want to change them), they default to SVG icons coded inline.
When I run the posted code I get a javascript error: Uncaught (in promise) ReferenceError: MarkerClusterer is not defined.
That is because according to the documentation when you include the library the way you are (<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"></script>), the constructor for the MarkerClusterer is accessed as:
When adding via unpkg, the MarkerClusterer can be accessed at markerClusterer.MarkerClusterer.
Changing that, makes the clusters appear.
proof of concept fiddle
code snippet:
var mymap;
var markers = [];
function initMap() {
var centerpoint = {
lat: 40.7127753,
lng: -74.0059728
}; //centered around New York City
mymap = new google.maps.Map(document.getElementById('gmap'), {
zoom: 4,
center: centerpoint
});
processCSV(data);
}
var data = '"","New York","New York^ NY","516-555-5555",40.7127753, -74.0059728\n"","Newark","Newark^ NJ","201-555-5555",40.735657, -74.1723667';
function processCSV(allData) {
console.log(allData);
const rows = allData.split('\n');
var storename, storephone, storeaddress, storelat, storelng;
for (let i = 0; i < rows.length; i++) {
var line = rows[i];
storename = line.split(",")[1];
storephone = line.split(",")[3];
storeaddress = String(line.split(",")[2]);
storeaddress = replaceAll(storeaddress, "^", ",");
storelat = line.split(",")[4];
storelng = line.split(",")[5];
createMarker(storename, storephone, storeaddress, storelat, storelng);
}
createCluster();
}
function replaceAll(string, search, replace) {
return string.split(search).join(replace);
}
function createCluster() {
var mcluster = new markerClusterer.MarkerClusterer({
map: mymap,
markers: markers
});
}
function createMarker(name, phone, address, latstr, lngstr) {
var contentString = "<b>" + name + "</b><br><br><i>" + phone + "</i><br><br>" + address;
var latLng = {
lat: Number(latstr),
lng: Number(lngstr)
};
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var marker = new google.maps.Marker({
position: latLng,
map: mymap,
title: name
});
markers.push(marker);
console.log("added marker to map" + name);
marker.addListener("click", () => {
infowindow.open({
anchor: marker,
map: mymap,
shouldFocus: false,
});
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#gmap {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="gmap"></div>
<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"></script>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>
</html>

Related

Algolia and google filter results based on user position

Hi I am using Google maps alongside algolia where I have an index 'locations' with 'lat' and 'lng'.
I am getting user location and watching position, I am also displaying markers from database based on lng and lat however I want to add a bit to it:
So I have followed that link:
https://www.algolia.com/doc/guides/geo-search/geo-search-overview/
And came up with:
#extends('master') #section('title', 'Live Oldham')
#section('extrafiles')
<script type="text/javascript" src="https://maps.google.com/maps/api/js?v=3&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50&language=en"></script>
<script type="text/javascript" src="{!! asset('js/homesearch.js') !!}"></script>
#endsection
#section('content')
<div id="map_canvas" style="height:600px;"></div>
#endsection
and js:
$(document).ready(function() {
var map;
function initializeMap(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function locError(error) {
// the current position could not be located
alert("The current position could not be found!");
}
function setCurrentPosition(position) {
currentPositionMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
),
title: "Current Position"
});
map.panTo(new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
));
}
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log(latitude);
console.log(longitude);
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition(position);
console.log(position);
}
function watchCurrentPosition(position) {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position,
)
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
}else{
alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
var APPLICATION_ID = '75RQSC1OHE';
var SEARCH_ONLY_API_KEY = 'f2f1e9bba4d7390fc61523a04685cf12';
var INDEX_NAME = 'locations';
var PARAMS = { hitsPerPage: 100 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
// Map initialization
var markers = [];
//alert("heelo");
var fitMapToMarkersAutomatically = true;
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
console.log(hit)
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
markers.push(marker);
}
// Automatically fit the map zoom and position to see the markers
if (fitMapToMarkersAutomatically) {
var mapBounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
mapBounds.extend(markers[i].getPosition());
}
map.fitBounds(mapBounds);
}
});
function renderHits(content) {
$('#container').html(JSON.stringify(content, null, 2));
}
algoliaHelper.setQueryParameter('aroundRadius', 5000).search(); // 5km Radius
});
However there are few problems with this that I don't know how to tackle:
When user is moving, it doesn't center the map on the marker.
At this moment marker jumps between location when user moves, I would like for the marker to dynamically move on the map when user moves.
I want to use algolia to dynamically set markers, so I want to show markers with 5km radius from user location, and dynamically add or remove markers that are outside it.
I can't help you much with those questions since it's mostly about how to use GMap JS lib and I'm not experienced with it. However, something else catched my eyes:
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
You should put your coordinates in the _geoloc field in order to be able to use the geo-search features. It looks like this:
_geoloc: {
lat: 40.639751,
lng: -73.778925
}

retrieving latitude and longitude from database(db2) and show in map in IBM worklight

I have saved latitude and longitude in database(db2).I want to use them to show their location in map.I am working with IBM Worklight and as database I am using DB2.
My problem is I can retrieve value from database,store it in a variable but could not be able to pass the value in the function of map where it can be used as latitude and longitude.
Any positive help would be appreciated.Thanks in advance.
My approach:
CODE:
var mylat;
var mylon;
var clat;
var clon;
function maplo() {
//database value,I have stored them in a text input type
clat=$("#lati").val();
clon=$("#long").val();
}
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
mylat=position.coords.latitude;
mylon=position.coords.longitude;
}
function success(position) {
//reload();
maplo();
showPosition(position);
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '460px';
mapcanvas.style.width = '320px';
document.querySelector('article').appendChild(mapcanvas);
var flat=clat;
var flon=clon;
alert("custom latitude is : "+flat);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var coords1 = new google.maps.LatLng(flat, flon);
var options = {
zoom: 16,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title:"You are here!"
});
var geolocation = new google.maps.Marker({
position: coords1,
map: map,
title: 'Your car location',
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
function searchcarl()
{
var a=$("#searchcar").val();
var invocationData={
adapter:'park',
procedure :'procedure4',
parameters:[a]
};
var options={
onSuccess:success6,
onFailure:fail6
};
WL.Client.invokeProcedure(invocationData, options);
}
function success6(result){
if((result.invocationResult.resultSet.length)>0)
{
alert("location fetching!");
var I=result.invocationResult.resultSet[0].LAT;
var J=result.invocationResult.resultSet[0].LON;
$("#lati").val(I);
$("#long").val(J);
}
else{
alert("Incorrect Username or Password!");
window.location.assign("#log");
}
}
function fail6()
{
alert("fail6");
}
I will update the code as follows:
// create a map global variable
var map;
function initMap(position) {
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '460px';
mapcanvas.style.width = '320px';
document.querySelector('body').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom : 16,
center : coords,
mapTypeControl : false,
navigationControlOptions : {
style : google.maps.NavigationControlStyle.SMALL
},
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position : coords,
map : map,
title : "You are here!"
});
}
// adds a marker to the map
function addCarLocationMarker(lat, lng) {
var coords = new google.maps.LatLng(lat, lng);
var geolocation = new google.maps.Marker({
position : cords,
map : map,
title : 'Your car location',
icon : 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
// once you know the user location, init the map
initMap(position);
});
} else {
alert('Geo Location is not supported');
}
function searchcarl() {
var a = $("#searchcar").val();
var invocationData = {
adapter : 'park',
procedure : 'procedure4',
parameters : [ a ]
};
var options = {
onSuccess : adapterSuccess,
onFailure : adapterFailed
};
WL.Client.invokeProcedure(invocationData, options);
}
function adapterSuccess(result) {
if ((result.invocationResult.resultSet.length) > 0) {
alert("location fetching!");
var I = result.invocationResult.resultSet[0].LAT;
var J = result.invocationResult.resultSet[0].LON;
// add the marker directly to the map
addCarLocationMarker(I, J);
}
else {
alert("Incorrect Username or Password!");
window.location.assign("#log");
}
}
function adapterFailed() {
alert("adapter invocation failed");
}
Like Idan mentioned, it's not a good idea to store the coordinates in text boxes to then use the text boxes as the source of the coordinates.
You should add the marker directly after you received the coordinates from the adapter. In this case I created a separate function initMap to initialize the map and center it on the current user's location. It is a good idea to make your functions smaller to perform one single task.
I removed some function that I thought you didn't need or were duplicating functionality namely maplo, getLocation and showPosition.

Google maps adding streetview to each infowindow

I would like to add streetview to each infowindow but I can't figure out how to integrate the code. I tried putting the code where the comments are set and that works half. Still have to learn a lot about programming.
html += '<div id="content" style="width:200px;height:200px;"></div>';
var pano = null;
google.maps.event.addListener(infoWindow, 'domready', function () {
if (pano != null) {
pano.unbind("position");
pano.setVisible(false);
}
pano = new google.maps.StreetViewPanorama(document.getElementById("content"), {
navigationControl: true,
navigationControlOptions: { style: google.maps.NavigationControlStyle.ANDROID },
enableCloseButton: false,
addressControl: false,
linksControl: false
});
pano.bindTo("point", marker);
pano.setVisible(true);
});
I'm using this code:
function load() {
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(41.640078, -102.669433),
zoom: 3,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("mymap.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/>" + point;
// comment *** streetview here ****
var marker = new google.maps.Marker({
map: map,
position: point
});
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);
});
}
Working example using DOM elements (rather than using string content):
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers used by the side_bar
var gmarkers = [];
// global "map" variable
var map = null;
var sv = new google.maps.StreetViewService();
var clickedMarker = null;
var panorama = null;
// Create the shared infowindow with three DIV placeholders
// One for a text string, oned for the html content from the xml, one for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var htmlContent = document.createElement("DIV");
content.appendChild(htmlContent);
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50),
content: content
});
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: name,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
marker.myHtml = html;
google.maps.event.addListener(marker, "click", function() {
clickedMarker = marker;
sv.getPanoramaByLocation(marker.getPosition(), 50, processSVData);
// openInfoWindow(marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length - 1) + ')">' + name + '<\/a><br>';
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var marker = clickedMarker;
openInfoWindow(clickedMarker);
if (!!panorama && !!panorama.setPano) {
panorama.setPano(data.location.pano);
panorama.setPov({
heading: 270,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
google.maps.event.addListener(marker, 'click', function() {
var markerPanoID = data.location.pano;
// Set the Pano to use the passed panoID
panorama.setPano(markerPanoID);
panorama.setPov({
heading: 270,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
});
}
} else {
openInfoWindow(clickedMarker);
title.innerHTML = clickedMarker.getTitle() + "<br>Street View data not found for this location";
htmlContent.innerHTML = clickedMarker.myHtml;
panorama.setVisible(false);
// alert("Street View data not found for this location.");
}
}
function initialize() {
// Create the map
// No need to specify zoom and center as we fit the map further down.
map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from example.xml
// downloadUrl("example.xml", function(doc) {
var xmlDoc = xmlParse(xmlData);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat, lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point, label, html);
bounds.extend(point);
}
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
// Zoom and center the map to fit the markers
map.fitBounds(bounds);
// });
}
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
var pin = new google.maps.MVCObject();
google.maps.event.addListenerOnce(infowindow, "domready", function() {
panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true
});
panorama.bindTo("position", pin);
});
// Set the infowindow content and display it on marker click.
// Use a 'pin' MVCObject as the order of the domready and marker click events is not garanteed.
function openInfoWindow(marker) {
title.innerHTML = marker.getTitle();
htmlContent.innerHTML = marker.myHtml;
pin.set("position", marker.getPosition());
infowindow.open(map, marker);
}
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
// from the v2 tutorial page at:
// http://econym.org.uk/gmap/basic3.htm
google.maps.event.addDomListener(window, 'load', initialize);
var xmlData = '<markers> <marker lat="43.65654" lng="-79.90138" html="Some stuff to display in the<br>First Info Window" label="Marker One" /> <marker lat="43.91892" lng="-78.89231" html="Some stuff to display in the<br>Second Info Window" label="Marker Two" /> <marker lat="43.82589" lng="-79.10040" html="Some stuff to display in the<br>Third Info Window" label="Marker Three" /></markers> ';
/**
* Parses the given XML string and returns the parsed document in a
* DOM data structure. This function will return an empty DOM node if
* XML parsing is not supported in this browser.
* #param {string} str XML string.
* #return {Element|Document} DOM.
*/
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
html,
body {
height: 100%;
}
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<!-- you can use tables or divs for the overall layout -->
<table border="1">
<tr>
<td>
<div id="map_canvas" style="width: 550px; height: 450px"></div>
</td>
<td valign="top" style="width:150px; text-decoration: underline; color: #4444ff;">
<div id="side_bar"></div>
</td>
</tr>
</table>

Google Maps v3 - Infowindow always assumes the last marker's position

I'm running into an issue with the position of my infowindows. I am generating the markers in a for-loop, but when I click on an infowindow, the position is always set to the marker that was generated last. The content is correct, however. It's definitely a scoping issue, and there is also a Drupal Ajax call that fetches the content (which doesn't contain any location info). Can anyone help? Here is the for-loop:
for ( markerItem in data ) {
var icon = icons[data[markerItem][3]].mouseOutIcon;
var image = icons[data[markerItem][3]].mouseOverImage;
var latlng = new google.maps.LatLng( data[markerItem][0], data[markerItem][1] );
var marker = new google.maps.Marker({
icon:icon,
clickable:true,
position: latlng,
map: map,
draggable:false,
title: data[markerItem][2]
});
marker.mapid = mapid;
marker.mid = data[markerItem][4];
google.maps.event.addListener(marker,'click',function(latlng) {
$.get('/map-info/'+this.mapid+'/'+this.mid, null, function(response) {
console.log('first' + marker.getPosition());
var result = Drupal.parseJson(response);
if ( result.status == 0 ) {
if(infowindow != null) {
infowindow.close();
}
infowindow = new google.maps.InfoWindow({
content: result.html
//position: marker.getPosition()
});
infowindow.open(map,marker);
}
});
google.maps.event.addListener(marker, 'mouseover', function(latlng) {
this.setImage( this.mouseOverImage );
});
google.maps.event.addListener(marker, 'mouseout', function(latlng) {
this.setImage( this.mouseOutImage );
});
});
marker.mouseOverImage = image;
marker.mouseOutImage = icon.image;
gmap.overlays.push( marker );
marker.setMap(map);
if ( checkboxState[data[markerItem][3]] ) {
marker.setMap(map);
}
else {
marker.setMap(null);
}
}
});
}
else {
console.log('inside else');
var lat3 = gmap.oldBounds.getSouthWest().lat();
var lng3 = gmap.oldBounds.getSouthWest().lng();
var lat4 = gmap.oldBounds.getNorthEast().lat();
var lng4 = gmap.oldBounds.getNorthEast().lng();
$.get('/map-markers/'+mapid+'/'+lat1+'/'+lng1+'/'+lat2+'/'+lng2+'/'+lat3+'/'+lng3+'/'+lat4+'/'+lng4, null, function(response) {
var result = Drupal.parseJson(response);
var data = result.markers;
for ( var i = 0; i < 4; i++ ) {
icons.push( { mouseOutIcon: Drupal.gmap.getIcon('boilers', i), mouseOverImage: mouseOverImage(Drupal.gmap.getIcon('boilers', i).image)});
}
var gmap = Drupal.gmap.getMap(mapid);
for ( markerItem in data ) {
var icon = icons[data[markerItem][3]].mouseOutIcon;
var image = icons[data[markerItem][3]].mouseOverImage;
var latlng = new GLatLng( data[markerItem][0], data[markerItem][1] );
var marker = createMarker(latlng, {icon: icon, title:data[markerItem][2], clickable:true, draggable:false }, data[markerItem][4] );
marker.mouseOverImage = image;
marker.mouseOutImage = icon.image;
gmap.overlays.push( marker );
map.addOverlay( marker );
if ( checkboxState[data[markerItem][3]] ) {
//marker.show();
}
else {
//marker.hide();
}
}
You have to use closures to solve this problem.
The below in a working sample
Use the JS method AddInfoWidnow from below code to add InfoWindow to a marker.
function AddInfoWidnow(marker,message)
{
var infowindow = new google.maps.InfoWindow({ content: message });
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(marker.get('map'), marker);
});
}
call the AddInfoWidnow method inside the for loop
function ShowOnMap(ContainerId, mapItems) {
var DefaultLatLng= new google.maps.LatLng('12.967461', '79.941824');
var mapOptions = {
center: DefaultLatLng,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
marker: true
};
var mapCust = new google.maps.Map(document.getElementById(ContainerId), mapOptions);
var arrJsonObject = JSON.parse(mapItems);
for (var y = 1; y <= arrJsonObject.length; y++)
{
var myLatLng1 = new google.maps.LatLng(arrJsonObject[y - 1].Latitude, arrJsonObject[y - 1].Lonngitude);
var marker = new google.maps.Marker({
position: myLatLng1,
map: mapCust,
title: 'Marked at '+ arrJsonObject[y - 1].markedDate
});
addInfoWindows(marker,y-1,arrJsonObject);
marker.setMap(mapCust);
}
}
Using the below snnipet I called it.
var mapItems='[
{
"Latitude": "22.575897",
"Lonngitude": "88.431754",
"CustomerCode": "*$$$*",
"CustomerName": "*###*",
"markedDate": "2/20/2014 12:04:41 PM"
},
{
"Latitude": "22.615067",
"Lonngitude": "88.431759",
"CustomerCode": "*$$$*",
"CustomerName": "*###*",
"markedDate": "2/20/2014 3:02:19 PM"
}
]';
ShowOnMap(containerId2, mapItems);
The thing is you have to add the info window using closure and This works for me.
Reference

Disable point-of-interest information window using Google Maps API v3

I have a custom map with an information bubble and custom markers. When I zoom into points of interest such as parks and universities appear and when I click an information window opens. How do I disable the info window?
My code is as follows:
var geocoder;
var map;
var infoBubble;
var dropdown = "";
var gmarkers = [];
var hostel_icon = new google.maps.MarkerImage('/resources/hostel_blue_icon.png',
new google.maps.Size(28,32),
new google.maps.Point(0,0),
new google.maps.Point(14,32));
var bar_icon = new google.maps.MarkerImage('/resources/bar_red_icon.png',
new google.maps.Size(28,32),
new google.maps.Point(0,0),
new google.maps.Point(14,32));
var icon_shadow = new google.maps.MarkerImage('/resources/myicon_shadow.png',
new google.maps.Size(45,32),
new google.maps.Point(0,0),
new google.maps.Point(12,32));
var customIcons = {
hostel: {
icon: hostel_icon,
shadow: icon_shadow
},
bar: {
icon: bar_icon,
shadow: icon_shadow
}
};
function initialize() {
var latlng = new google.maps.LatLng(12.82364, 26.29987);
var myMapOptions = {
zoom: 2,
center: latlng,
panControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR},
navigationControlOptions: {style: google.maps.NavigationControlStyle.DEFAULT}
}
map = new google.maps.Map(document.getElementById("map_canvas"), myMapOptions);
infoBubble = new InfoBubble({
shadowStyle: 0,
padding: 0,
backgroundColor: 'rgb(57,57,57)',
borderRadius: 5,
arrowSize: 10,
borderWidth: 1,
maxWidth: 400,
borderColor: '#2c2c2c',
disableAutoPan: false,
hideCloseButton: true,
arrowPosition: 50,
backgroundClassName: 'phoney',
arrowStyle: 0
});
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml_2.php", function(data) {
var xml = parseXml(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var bar_name = markers[i].getAttribute("bar_name");
var hostel_name = markers[i].getAttribute("hostel_name");
var street = markers[i].getAttribute("street");
var city = markers[i].getAttribute("city");
var postcode = markers[i].getAttribute("postcode");
var country = markers[i].getAttribute("country");
var page = markers[i].getAttribute("page");
var map_photo = markers[i].getAttribute("map_photo");
var type = markers[i].getAttribute("type");
var category = markers[i].getAttribute("category");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = '<div class="infowindow"><div class="iwPhoto" style="width: 105px; height: 65px;">' + "' + "<a href='" + page + "'>" + hostel_name + "" + '</div><div class="iwCategory" style="height: 15px;">' + category + '</div><div class="iwCity" style="height: 29px;">' + "' + "<a href='" + page + "'><img src='/resources/arrow.png'/>" + '</div></div></div>';
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
title: bar_name
});
marker.bar_name = bar_name;
marker.category = category;
bindInfoBubble(marker, map, infoBubble, html, bar_name);
gmarkers.push(marker);
str = '<option selected> - Select a club - </option>';
for (j=0; j < gmarkers.length; j++){
str += '<option value="'+gmarkers[j].bar_name+'">'+gmarkers[j].bar_name+', '+gmarkers[j].category+'</option>';
}
var str1 ='<form name="form_city" action=""><select style="width:150px;" id="select_city" name="select_cityUrl" onchange="handleSelected(this);">';
var str2 ='</select></form>';
dropdown = str1 + str + str2;
}
document.getElementById("dd").innerHTML = dropdown;
});
}
function handleSelected(opt) {
var indexNo = opt[opt.selectedIndex].index;
google.maps.event.trigger(gmarkers[indexNo-1], "click");
}
function bindInfoBubble(marker, map, infoBubble, html) {
google.maps.event.addListener(marker, 'click', function() {
infoBubble.setContent(html);
infoBubble.open(map, marker);
google.maps.event.addListener(map, "click", function () {
infoBubble.close();
});
});
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
UPDATE Google Maps JavaScript API V3
You can set clickableIcons to false in MapOptions. This will keep the POI icons but disable the infowindows just as you want.
function initialize() {
var myMapOptions = { clickableIcons: false }
}
Further details here...
https://developers.google.com/maps/documentation/javascript/3.exp/reference#MapOptions
See the other answers for the clickable: false answer.
However, if you want it clickable, but no infowindow, call stop() on the event to prevent the infowindow from showing, but still get the location info:
map.addListener('click', function (event) {
// If the event is a POI
if (event.placeId) {
// Call event.stop() on the event to prevent the default info window from showing.
event.stop();
// do any other stuff you want to do
console.log('You clicked on place:' + event.placeId + ', location: ' + event.latLng);
}
}
For more info, see the docs.
Other option: completely remove the POI-icons, and not only the infoWindow:
var mapOptions = {
styles: [{ featureType: "poi", elementType: "labels", stylers: [{ visibility: "off" }]}]
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
You can do this by creating a styled map without labels for the points of interest.
This maintains the topography and other nice pieces of information on the map, but removes the markers.
var remove_poi = [
{
"featureType": "poi",
"elementType": "labels",
"stylers": [
{ "visibility": "off" }
]
}
]
map.setOptions({styles: remove_poi})
You could consider the following approach to disable POI Info Window:
function disablePOIInfoWindow(){
var fnSet = google.maps.InfoWindow.prototype.set;
google.maps.InfoWindow.prototype.set = function () {
};
}
Example
function initMap() {
var latlng = new google.maps.LatLng(40.713638, -74.005529);
var myOptions = {
zoom: 17,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
disablePOIInfoWindow();
}
function disablePOIInfoWindow(){
var fnSet = google.maps.InfoWindow.prototype.set;
google.maps.InfoWindow.prototype.set = function () {
alert('Ok');
};
}
google.maps.event.addDomListener(window, 'load', initMap);
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map_canvas"></div>
The above example affects all the info windows, so if you need to disable only POI Info Window, then we could introduce flag to determine whether it is POI Info Window or not:
function disablePOIInfoWindow(){
var fnSet = google.maps.InfoWindow.prototype.set;
google.maps.InfoWindow.prototype.set = function () {
if(this.get('isCustomInfoWindow'))
fnSet.apply(this, arguments);
};
}
Example
function initMap() {
var latlng = new google.maps.LatLng(40.713638, -74.005529);
var myOptions = {
zoom: 17,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infowindow = new google.maps.InfoWindow({
content: ''
});
infowindow.set('isCustomInfoWindow',true);
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
disablePOIInfoWindow();
google.maps.event.addListener(map, 'click', function (event) {
infowindow.setContent(event.latLng.lat() + "," + event.latLng.lng());
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
function disablePOIInfoWindow(){
var fnSet = google.maps.InfoWindow.prototype.set;
google.maps.InfoWindow.prototype.set = function () {
if(this.get('isCustomInfoWindow'))
fnSet.apply(this, arguments);
};
}
//google.maps.event.addDomListener(window, 'load', initMap);
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
height: 100%;
}
<div id="map_canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
async defer></script>
Simply style the map to not show Points of Interest. This is simple and does not breach Google's terms of service.
eg
mapOpts = {
styles: [
{
featureType: "poi",
stylers: [
visibility: "off"
]
}
]
};
$("#my-map").gmap(mapOpts).on("init", function(evt, map){
// do stuff with the initialised map
});
If you want the data without getting the InfoWindow HTML showing at all, you simply have to re-work the prototype of google.maps.InfoWindow:
google.maps.InfoWindow.prototype.open = function () {
return this; //prevent InfoWindow to appear
}
google.maps.InfoWindow.prototype.setContent = function (content) {
if (content.querySelector) {
var addressHTML = content.querySelector('.address');
var address = addressHTML.innerHTML.replace(/<[^>]*>/g, ' ').trim();
var link = content.querySelector('a').getAttribute('href');
var payload = {
header: 'event',
eventName: 'place_picked',
data: {
name: content.querySelector('.title').innerHTML.trim(),
address: address,
link: link
}
};
console.log('emit your event/call your function', payload);
}
};
We can do it by handling clicks on poi, Google api has provided a way to detect clicks on POI as per this article
Based on article above Here is a simpler version of code that can be used to stop the clicks on POI
function initMap() {
map = new google.maps.Map(document.getElementById('map'), myOptions);
var clickHandler = new ClickEventHandler(map, origin);
}
var ClickEventHandler = function (map, origin) {
this.origin = origin;
this.map = map;
this.map.addListener('click', this.handleClick.bind(this));
};
ClickEventHandler.prototype.handleClick = function (event) {
//console.log('You clicked on: ' + event.latLng);
if (event.placeId) {
//console.log('You clicked on place:' + event.placeId);
// Calling e.stop() on the event prevents the default info window from
// showing.
// If you call stop here when there is no placeId you will prevent some
// other map click event handlers from receiving the event.
event.stop();
}
}