I have a map that I have been trying to figure out adding infoWindow's to markers that live in an array and I am stuck.. With a single map and a single marker I can add an info window no problem. But for the life of me I CAN NOT get the infowindows to work within my array. If anyone could possibly help me get this to work I would be forever greatful. My intentions is to be able to pull html within the infowindows. Here is a fiddle with where I am at so far.
var map;
var markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 14,
center: new google.maps.LatLng(-33.91721, 151.22630),
mapTypeId: 'roadmap',
disableDefaultUI: true
});
// var iconBase = <?php echo "'/images/markers/'"; ?>;
var icons = {
typea: {
icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
},
typeb: {
icon: "http://maps.google.com/mapfiles/ms/micons/green.png"
},
typec: {
icon: "http://maps.google.com/mapfiles/ms/micons/orange.png"
}
};
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map,
type: feature.type
});
marker.addListener('click', function() {
//set zoom level
map.setZoom(20);
//center map
map.setCenter(marker.getPosition());
alert("Testing");
});
markers.push(marker);
}
filterMarkers = function(getType) {
console.log(getType);
for (var i = 0; i < markers.length; i++) {
if (markers[i].type == getType || getType == "") {
markers[i].setVisible(true);
} else {
markers[i].setVisible(false);
}
}
}
var features = [{
position: new google.maps.LatLng(-33.91721, 151.22630),
type: 'typea'
}, {
position: new google.maps.LatLng(-33.91539, 151.22820),
type: 'typeb'
}, {
position: new google.maps.LatLng(-33.91747, 151.22912),
type: 'typec'
}];
for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}
}
google.maps.event.addDomListener(window, "load", initMap);
Complete working fiddle: http://jsfiddle.net/h80vtmye/
GoogleMap not allow to use infowindow like that. Create a single copy of the infowindow instead of maintaining an array and set contents with infowindow.setContent() during the mouseover event of marker.
Related
I am a student trying to become a java developer in Korea
I want to draw a polyline connecting the markers with a click event, not with directions.
I'll give you an exampleenter image description here
It's not finished yet, but I'll show you what I made
I made a mistake but please understand
What I want is to draw a polyline by connecting two fixed markers.
var map, polyline,markers = new Array();
var stockholm = {lat:45,lng:10}; // 맵 중앙 설정
function initMap(){
// map options
var options = {
zoom:4,
center:stockholm,
streetViewControl: true,
draggable:true,
mapTypeId: "roadmap",
// 맵 기본 컨트롤 설정
mapTypeControl: true,
mapTypeControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_TOP
},
scaleControl: true
}
// Map 호출 ======================================================================
map = new google.maps.Map(document.getElementById('map'),options);
// polyline 옵션 지정 ============================================================
polyline = new google.maps.Polyline({
strokeColor: 'red',
strokeWeight: 3,
map: map
});
google.maps.event.addListener(map, 'click', function (event) {
addPoint(event.latLng);
});
// searchbox===================
const input = document.getElementById("pac-input");
const searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
let markers1 = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener("places_changed", () => {
const places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers1.forEach((marker) => {
marker.setMap(null);
});
markers1 = [];
// For each place, get the icon, name and location.
const bounds = new google.maps.LatLngBounds();
places.forEach((place) => {
if (!place.geometry || !place.geometry.location) {
console.log("Returned place contains no geometry");
return;
}
const 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(25, 25),
};
// Create a marker for each place.
markers1.push(new google.maps.Marker({
map,
icon,
title: place.name,
position: place.geometry.location,
}));
if (place.geometry.viewport) {
bounds.union(place.geometry.viewport);
}else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
// 고정 마커 추가
var markers = [
// 가나
{
coords:{lat:6.6666004, lng:-1.6162709},
iconImage:'assets/img/places/stparkdublin.png',
content:'<div style="height:auto;width:400px;"><h1>가나-쿠마시</h1>쿠마시는 가나 아샨티 주의 주도이며 구 아샨티 왕국의 수도였다. 수도인 아크라에서 북서쪽으로 약 250km 떨어져 있다. 쿠마시는 적도로부터 북쪽으로 약 482km, 기니만으로터 북쪽으로 약 160km 에 위치한다.',
},
{
coords:{lat:5.6037168,lng:-0.1869644},
iconImage:'assets/img/places/botanic garden.png',
content:'<div style="height:auto;width:400px;"><h1>가나-아크라</h1>아크라는 가나 공화국의 수도이자 약 227만 명의 인구를 가진 가나 최대의 도시이다. 도시 자체도 아크라 메트로폴리스 특구에 속해 있으며, 그 면적은 약 139km²이다. 아크라의 관광지 중에 가나 국립 박물관이 있다. 코토카 국제공항이 있다.',
},
{
coords:{lat:5.1315, lng:-1.2794744},
iconImage:'assets/img/places/stparkdublin.png',
content:'<div style="height:auto;width:400px;"><h1>가나-케이프코스트</h1>케이프코스트는 가나의 항구 도시로, 중앙 주의 주도이다. 16세기부터 영국과 포르투갈, 스웨덴, 덴마크, 네덜란드의 통치를 받았다. 15세기 포르투갈이 이 곳을 발견했으며 1653년 스웨덴이 케이프코스트 성을 건설했다. 이 성은 현재 세계유산으로 지정되어 있다.',
},
{
coords:{lat:9.393908, lng:-0.8556313999999999},
iconImage:'assets/img/places/swordscastle.png',
content:'<div style="height:auto;width:400px;"><h1>가나-타말레</h1>타말레은 가나 북부 주의 주도이다. 인구는 55만명이다.',
},
{
coords:{lat:10.7875419, lng:-0.8579818},
iconImage:'assets/img/places/Howth.png',
content:'<div style="height:auto;width:400px;"><h1>가나-볼가탕가</h1>볼가탕가는 가나의 도시이다. 경작과 가축 사육이 주된 생업이다.',
},
];
var gmarkers = [];
for(var i = 0; i < markers.length; i++){
gmarkers.push(addMarker(markers[i]));
}
const sidebar = document.getElementById("sidebar"); // sidebar
var activeInfoWindow = null;
//Add MArker function
function addMarker(props){
var marker = new google.maps.Marker({
position:props.coords,
map:map,
descrip:props.content,
});
//Check content
if(props.content){
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('click',function(){
infoWindow.open(map,marker);
for(var i=0;i<markers.length;i++){
sidebar.innerHTML = props.content;
}
});
marker.addListener('click', function () {
if (activeInfoWindow) { activeInfoWindow.close();}
infoWindow.open(map, marker);
activeInfoWindow = infoWindow;
});
}
return marker;
}
var markerCluster = new MarkerClusterer(map, gmarkers,
{
imagePath:'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
gridSize:100,
minClusterSize:10,
});
}
google.maps.event.addDomListener(window, 'load', initMap);
//poly line ======================================================================
var latlnglatlng = new Array;
function removePoint(marker) {
for (var i = 0; i < markers.length; i++) {
if (markers[i] === marker) {
markers[i].setMap(null);
markers.splice(i, 1);
polyline.getPath().removeAt(i);
}
}
}
function addPoint(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
markers.push(marker);
//console.log(markers.position.lng.Scopes);
polyline.getPath().setAt(markers.length - 1, latlng);
google.maps.event.addListener(marker, 'click', function (event) {
removePoint(marker);
});
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDjtW34Ax16khc7UYth6--V4pNFX1XlHUE&libraries=places"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
Thanks again for watching I really want to solve this, I've been thinking about it for a month
I can open web link from marker by
google.maps.event.addListener(marker, "click", function() {
window.open('http://example.com/');
});
But what if I need to place 100 markers with 100 links to Google Maps?
My array with coordinates and links looks like this
var point = [[52.7081444444445, 58.6677361111111, "Sib/2377/index.html"],
[52.7039611111111, 58.668425, "Sib/2378/index.html"],
[52.6993166666667, 58.6680305555556, "Sib/2379/index.html"],
[52.6946277777778, 58.6679416666667, "Sib/2380/index.html"],
[52.6947833333333, 58.6755555555556, "Sib/2381/index.html"]];
add the URL as a property of the marker (.url). Open the window using this.url
for (var i = 0; i < points.length; i++) {
var point = points[i];
var marker = new google.maps.Marker({
position: {
lat: point[0],
lng: point[1]
},
map: map,
url: point[2]
});
google.maps.event.addListener(marker, "click", function() {
window.open(this.url);
});
}
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: -33.9,
lng: 151.2
}
});
setMarkers(map);
}
// Data for the markers consisting of a Latitude, a Longitude and a URL.
var points = [
[52.7081444444445, 58.6677361111111, "http://www.google.com"],
[52.7039611111111, 58.668425, "http://www.yahoo.com"],
[52.6993166666667, 58.6680305555556, "http://maps.google.com"],
[52.6946277777778, 58.6679416666667, "http://maps.google.com?q=52.6946277777778,58.6679416666667"],
[52.6947833333333, 58.6755555555556, "http://maps.google.com?q=52.6947833333333,58.6755555555556"]
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
// Adds markers to the map.
for (var i = 0; i < points.length; i++) {
var point = points[i];
var marker = new google.maps.Marker({
position: {
lat: point[0],
lng: point[1]
},
map: map,
url: point[2]
});
google.maps.event.addListener(marker, "click", function() {
window.open(this.url);
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
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>
How do I toggle the visibility of a subset of markers in Google Maps API?
I have two sets of marker location data. Want to add a button to toggle visibility of each set independently.
Full code below for convenience. I have a button code in the header.
<button onclick="toggleMELocations()">Toggle ME Locations</button>`
The button is showing up, but clicking does not yield the expected result (ME locations disappearing).
The relevant function is "toggleMELocations." I am trying to say that if ME locations are currently visible, make them invisible. And vice versa.
Any help is much appreciated.
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: 40,
lng: -95
},
styles: [{
stylers: [{
saturation: -100
}]
}]
});
setMarkers(map);
}
function toggleMELocations() {
if (MEs) {
for (i in MEs) {
var visibility = (MEs[i].getVisible() == true) ? false : true;
MEs[i].setVisible(visibility);
}
}
}
// MEC locations
var MEs = [
['aaa', 36.07, -75.79],
['bbb', 40.07, -83.79]
];
// CC locations
var Concentras = [
['xxx', 38.01, -75.55],
['yyy', 30.10, -90.3]
];
function setMarkers(map) {
// Adds markers to the map.
for (var i = 0; i < MEs.length; i++) {
var ME = MEs[i];
var marker = new google.maps.Marker({
position: {
lat: ME[1],
lng: ME[2]
},
icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
map: map,
title: ME[0]
});
}
for (var i = 0; i < Concentras.length; i++) {
var Concentra = Concentras[i];
var marker = new google.maps.Marker({
position: {
lat: Concentra[1],
lng: Concentra[2]
},
icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
map: map,
title: Concentra[0]
});
}
}
Firstly getVisible() is not a valid function.
You need to add a global variable defined: var addedMEs = [];
This acts as an array of markers that have been added to the map in the setMarkers method. We change the setMarkers method to include a line which will add a marker object to the array defined above:
for (var i = 0; i < MEs.length; i++) {
var ME = MEs[i];
var marker = new google.maps.Marker({
position: {
lat: ME[1],
lng: ME[2]
},
icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
map: map,
title: ME[0]
});
addedMEs.push(marker);
}
Then we need to remove the getVisible() method as it is invalid. we change this line to:
var bounds = map.getBounds();
var visibility = (bounds.contains(addedMEs[i].position) == true) ? false : true;
addedMEs[i].setVisible(visibility);
And it works. :]
Here is the JSFiddle to try: https://jsfiddle.net/cmjcs5eL/13/
I got infowindows working, but for some reason if I click the same marker multiple clicks it opens multiple of the same infowindow. I have a feeling it has to be something with my code, but I cant quite put my finger on what it is. Any help is appreciated.
var map;
var markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 14,
center: new google.maps.LatLng(33.6894120, -117.9872660),
mapTypeId: 'roadmap',
disableDefaultUI: true
});
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map,
type: feature.type,
title: feature.title,
description: feature.description
});
marker.addListener('click', function() {
map.setCenter(marker.getPosition());
var infoWindow = new google.maps.InfoWindow({
map: map,
pixelOffset: new google.maps.Size(0, -60)
});
infoWindow.setContent(marker.description);
infoWindow.setPosition(marker.position);
google.maps.event.addListener(map, 'drag', function() {
infoWindow.close();
});
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
});
markers.push(marker);
}
filterMarkers = function(getType) {
//console.log(getType);
for (var i = 0; i < markers.length; i++) {
if (markers[i].type == getType || getType == "") {
markers[i].setVisible(true);
} else {
markers[i].setVisible(false);
}
}
}
var features = [
{
position: new google.maps.LatLng(-33.91721, 151.22630),
type: 'type1',
description: 'Description1'
},{
position: new google.maps.LatLng(-33.91721, 151.22630),
type: 'type2',
description: 'Description2'
},{
position: new google.maps.LatLng(-33.91721, 151.22630),
type: 'type3',
description: 'Description3'
}
];
for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}
}
$(document).ready(function(){
initMap();
});
If you don't want an infowindow created every time you click on the marker, don't create a new one every time you click on the marker, create one for the marker (or one for the map, if you only ever want one open), and open it in the click listener.
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
map: map,
type: feature.type,
description: feature.description
});
// create infowindow for the marker
var infoWindow = new google.maps.InfoWindow({});
marker.addListener('click', function() {
map.setCenter(marker.getPosition());
// set the content of the infowindow
infoWindow.setContent(marker.description);
// open the infowindow on the marker.
infoWindow.open(map,marker);
});
markers.push(marker);
}
proof of concept fiddle
You are creating a new InfoWindow with every marker click:
marker.addListener('click' ...
var infoWindow = *new google.maps.InfoWindow( ...*
It is expected that you get multiple instances.
If you want one InfoWindow for all markers you can follow this example
If you want to have one per each marker check out this SO answer.
I have three arrays : myLats, (latitudes) myLngs (longitudes) and myLocs (address strings)
e.g. myLats[0] = 53.3534751, ,myLngs[0] = -2.5682085, myLocs[0] = Longwood Rd Appleton Warrington. So the elements of each array all correspond to each other numerically.
When constructing the map in my initialize() function, I loop through these to place multiple markers at the correct coordinates, and i'm also trying to have each marker having an infowindow appear when clicked, yet when i click a marker an infowindow simply does not appear. Any help with this would be greatly appreciated.
Code:
function initialize() {
var myOptions = {
center: new google.maps.LatLng(54.00366, -2.547855),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var marker, infowindow, i;
for (i = 0; i <= myLats.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(myLats[i], myLngs[i]),
map: map,
clickable: true,
icon: '". url::base() ."resources/icons/accident.png',
});
infowindow = new google.maps.InfoWindow({
content: myLocs[i],
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
}
That's a common problem when dealing with more than one marker. You aren't in fact creating a new window for each marker but must redefining the single window for each marker.
You'll find the problem and solution on page 88 onwards of Google Map API V3
If you are new to Google Maps API, I would recommend reading that book, it gave me a great start and I avoided a lot of the "common" mistakes.
Hope this helps.
Jim
I made a few changes, like adding the markers inside a function, adding 'var', and changing i <= myLats.length to i < myLats.length. It was a combination of these changes that made it work.
var myLats = [ 54.20366, 54.42366, 54.64366];
var myLngs = [ -2.54788, -2.66788, -2.78788];
var myLocs = [ "Loc a" , "Loc b" , "Loc c"];
function initialize()
{
var myOptions =
{
center: new google.maps.LatLng(54.00366,-2.547855),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
var marker, infowindow, i;
for (i=0; i < myLats.length; i++)
{
addMarker(i);
}
function addMarker(i) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(myLats[i],myLngs[i]),
map: map,
clickable: true,
//icon: '". url::base() ."resources/icons/accident.png',
});
var infowindow = new google.maps.InfoWindow({
content: myLocs[i]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
}
However, I'm guessing you want a solution that keeps only one infowindow open, I had this figured out first:
var myLats = [ 54.20366, 54.42366, 54.64366];
var myLngs = [ -2.54788, -2.66788, -2.78788];
var myLocs = [ "Loc a" , "Loc b" , "Loc c"];
var map, marker, infowindow, i;
function initialize()
{
var myOptions =
{
center: new google.maps.LatLng(54.00366,-2.547855),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
infowindow = new google.maps.InfoWindow({ });
for (i = 0; i < myLats.length; i++) {
addMarker(i);
}
}
function addMarker(i) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(myLats[i],myLngs[i]),
map: map,
clickable: true
//icon: '". url::base() ."resources/icons/accident.png'
});
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(myLocs[i]);
infowindow.open(map,marker);
});
}