Related
I have Google Maps with many markers.
This is my code:
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding_all_2">
<div class="apartament_atrakcje">Atrakcja 1 pl</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding_all_2">
<div class="apartament_atrakcje">Atrakcja 2 PL</div>
</div>
<div id="map_canvas"></div>
<script>
window.onload = function () {
var styles = [{"featureType":"all"}];
var bounds = new google.maps.LatLngBounds();
var options = {
mapTypeControlOptions: {
mapTypeIds: ['Styled']
},
center: new google.maps.LatLng(11, 22),
zoom: 15,
disableDefaultUI: true,
mapTypeId: 'Styled'
};
marker = new google.maps.Marker({
map:map,
});
var div = document.getElementById('map_canvas');
var map = new google.maps.Map(div, options);
var styledMapType = new google.maps.StyledMapType(styles, { name: 'Styled' });
var markers = [
['Atrakcja 1 pl', 51.73925413, 19.51309225, 'Atrakcja 1 pl', '#', 'poi.png'],
['Atrakcja 2 PL', 53.41475000, 14.60220358, 'Atrakcja 2 PL', '#', 'poi.png'],
['Biskupia', 51.93780943, 15.52505514, 'Biskupia', '#', 'poi2.png']
];
var infoWindow= new google.maps.InfoWindow({maxWidth:600}),
marker, i,
image = 'http://localhost/apartamenty/assets/poi.png';
for( i = 0; i < markers.length; i++ ) {
var beach = markers[i];
var position = new google.maps.LatLng(beach[1], beach[2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
icon: 'http://localhost/apartamenty/assets/' + beach[5],
title: beach[0],
myurl: beach[4]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(''+marker['title']+'');
infoWindow.open(map, marker);
}
})(marker, i));
map.fitBounds(bounds);
map.mapTypes.set('Styled', styledMapType);
}
}
</script>
I have a map and the markers on it. This is ok!
After clicking on link obj-1 or obj-2 I would like to:
- center the map on this one, selected marker
- display the marker of this marker
If the user clicks on the link "Atrakcja 1 pl" - then map is center on marker with title Atrakcja 1 pll and his hint would be visible.
Does anyone know how to do it in my code?
One option would be to keep references to the markers in an array and add DOM click listeners to your "links" to open the marker's InfoWindow and center the map on that marker.
create an array of markers:
var gmarkers=[];
for (i = 0; i < markers.length; i++) {
var beach = markers[i];
var position = new google.maps.LatLng(beach[1], beach[2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
// icon: 'http://localhost/apartamenty/assets/' + beach[5],
title: beach[0],
myurl: beach[4]
});
gmarkers.push(marker);
// ...
add click listeners to your "links" that opens that marker's InfoWindow and centers the map on its position:
if (document.getElementById('obj-'+(i+1))) {
// relies on the naming convention in your posted code
google.maps.event.addDomListener(document.getElementById('obj-'+(i+1)), 'click', function(i) {
return function() {
google.maps.event.trigger(gmarkers[i], 'click');
map.setCenter(gmarkers[i].getPosition());
}}(i))
}
proof of concept fiddle
code snippet:
html,
body,
#map_canvas {
height: 90%;
width: 100%;
padding: 0px;
margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding_all_2">
<a href="#" class="obj-1" id="obj-1">
<div class="apartament_atrakcje">Atrakcja 1 pl</div>
</a>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding_all_2">
<a href="#" class="obj-2" id="obj-2">
<div class="apartament_atrakcje">Atrakcja 2 PL</div>
</a>
</div>
<div id="map_canvas"></div>
<script>
window.onload = function() {
var styles = [{
"featureType": "all"
}];
var gmarkers = [];
var bounds = new google.maps.LatLngBounds();
var options = {
mapTypeControlOptions: {
mapTypeIds: ['Styled']
},
center: new google.maps.LatLng(11, 22),
zoom: 15,
disableDefaultUI: true,
mapTypeId: 'Styled'
};
marker = new google.maps.Marker({
map: map,
});
var div = document.getElementById('map_canvas');
var map = new google.maps.Map(div, options);
var styledMapType = new google.maps.StyledMapType(styles, {
name: 'Styled'
});
var markers = [
['Atrakcja 1 pl', 51.73925413, 19.51309225, 'Atrakcja 1 pl', '#', 'poi.png'],
['Atrakcja 2 PL', 53.41475000, 14.60220358, 'Atrakcja 2 PL', '#', 'poi.png'],
['Biskupia', 51.93780943, 15.52505514, 'Biskupia', '#', 'poi2.png']
];
var infoWindow = new google.maps.InfoWindow({
maxWidth: 600
}),
marker, i,
image = 'http://localhost/apartamenty/assets/poi.png';
for (i = 0; i < markers.length; i++) {
var beach = markers[i];
var position = new google.maps.LatLng(beach[1], beach[2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
// icon: 'http://localhost/apartamenty/assets/' + beach[5],
title: beach[0],
myurl: beach[4]
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent('' + marker['title'] + '');
infoWindow.open(map, marker);
}
})(marker, i));
map.fitBounds(bounds);
map.mapTypes.set('Styled', styledMapType);
if (document.getElementById('obj-' + (i + 1))) {
// relies on the naming convention in your posted code
google.maps.event.addDomListener(document.getElementById('obj-' + (i + 1)), 'click', function(i) {
return function() {
google.maps.event.trigger(gmarkers[i], 'click');
map.setCenter(gmarkers[i].getPosition());
}
}(i))
}
}
}
</script>
I have an auto-opening infoWindow.
I wish only two were opened automatically, while one did not. The effect Just like in the pictures.
My Code:
<script>
function initialize() {
var openedInfoWindow = [];
var locations = [
['Oddział', 52.846190, 17.723237, 3],
['Oddział', 52.812224, 17.201023, 2],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1]
];
var cityCircle;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3]),
map: map,
content: locations[i][0]
});
bounds.extend(marker.position);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i, infowindow) {
return function () {
if(openedInfoWindow[i] != null){
openedInfoWindow[i].close();
openedInfoWindow[i] = null;
}else{
infowindow.setContent(this.content);
infowindow.open(map, this);
openedInfoWindow[i] = infowindow;
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow[i] = null;
});
}
}
})(marker, i, infowindow));
google.maps.event.trigger(marker, 'click');
}
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(9);
google.maps.event.removeListener(listener);
});
}
function loadScript() {
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyADTnbl7e9y2o13cXkUFO8RZpXFJI-yzp4&' + 'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>`
Picture 1 = so now
Picture 2 = so it has to be
I would suggest you generalize it, add a member to your array to determine whether to open the marker or not.
var locations = [
// IW content, lat, lng, nowrap, open IW
['Oddział', 52.846190, 17.723237, 3, true],
['Oddział', 52.812224, 17.201023, 2, true],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1, false]
];
Then do this to open the infowindow:
if (locations[i][4]) {
google.maps.event.trigger(marker, 'click');
}
proof of concept fiddle
code snippet:
function initialize() {
var openedInfoWindow = [];
var locations = [
['Oddział', 52.846190, 17.723237, 3, false],
['Oddział', 52.812224, 17.201023, 2, true],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1, true]
];
var cityCircle;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3]),
map: map,
content: locations[i][0]
});
bounds.extend(marker.position);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i, infowindow) {
return function() {
if (openedInfoWindow[i] != null) {
openedInfoWindow[i].close();
openedInfoWindow[i] = null;
} else {
infowindow.setContent(this.content);
infowindow.open(map, this);
openedInfoWindow[i] = infowindow;
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow[i] = null;
});
}
}
})(marker, i, infowindow));
if (locations[i][4]) {
google.maps.event.trigger(marker, 'click');
}
}
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() {
map.setZoom(9);
google.maps.event.removeListener(listener);
});
}
function loadScript() {
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?' + 'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
Below is my javascript code to display one marker point on google maps.
How can I display two marker points instead?
window.onload = function () {
'use strict';
var latlng = new google.maps.LatLng(17.497859,78.391293);
var styles = [];
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false
};
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h4>We Are Here</h4>'+
'<p>test'</p>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var map = new google.maps.Map(document.getElementById('map'), myOptions);
var myLatlng = new google.maps.LatLng(17.497859,78.391293);
var image = '../images/marker.png';
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!',
icon: image
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
Just add new instance of google.maps.Marker with its own position, title and infowindow and assign that to your map with map attribute or setMap(map) method of Marker object.
Just like next
var infowindow1 = new google.maps.InfoWindow({
content: contentString
});
var infowindow2 = new google.maps.InfoWindow({
content: contentString
});
var myLatlng1 = new google.maps.LatLng(17.497859,78.391293);
var myLatlng2 = new google.maps.LatLng(17.497859,78.391293);
var image = '../images/marker.png';
var marker1 = new google.maps.Marker({
position: myLatlng1,
map: map,
title: 'Hello World!',
icon: image
});
var marker2 = new google.maps.Marker({
position: myLatlng2,
map: map,
title: 'Hello World!',
icon: image
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.open(map,marker1);
});
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map,marker2);
});
<script type="text/javascript">
var locations = [
['ModelTown Lahore', 31.484665, 74.326204, 4],
['TownShip Lahore', 31.451794, 74.306549, 5],
['GreenTown Lahore', 31.435684, 74.304661, 3],
['Mughalpura Lahore', 31.573261, 74.363712, 2],
['WapdaTown Lahore', 31.425724, 74.266895, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: new google.maps.LatLng(31.435684, 74.304661),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
animation: google.maps.Animation.BOUNCE,
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
Please use the following code to plot any number of markers ;-)
`<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Google Map</title>
<style>
#map{
height: 600px;
width: 100%;
}
</style>
</head>
<body>
<h1>My Google Map`</h1>
<div id="map"></div>
<script>
function initMap(){
//Map options
var options = {
zoom:9,
center:{lat:42.3601, lng:-71.0589}
}
// new map
var map = new google.maps.Map(document.getElementById('map'), options);
// customer marker
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png';
//array of Marrkeers
var markers = [
{
coords:{lat: 42.4668, lng: -70.9495},img:iconBase,con:'<h3> This Is your Content <h3>'
},
{
coords:{lat: 42.8584, lng: -70.9300},img:iconBase,con:'<h3> This Is your Content <h3>'
},
{
coords:{lat: 42.7762, lng: -71.0773},img:iconBase,con:'<h3> This Is your Content <h3>'
}
];
//loopthrough markers
for(var i = 0; i <markers.length; i++){
//add markeers
addMarker(markers[i]);
}
//function for the plotting markers on the map
function addMarker (props){
var marker = new google.maps.Marker({
position: props.coords,
map:map,
icon:props.img
});
var infoWindow = new google.maps.InfoWindow({
content:props.con,
});
marker.addListener("click", () => {
infoWindow.open(map, marker);
});
}
}
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAVR9eQglFrAKCpuSWlnCV9Ao9QXEwJJCA&callback=initMap"
defer
></script>
</body>
</html>
`
I've been stuck on this issue for a while now and could really use some help. In a Google Map, I have a list of markers which are being treated as a markerArray, with their own custom icons. But along with displaying those markers, I would like for it to create a marker which is placed at the users geotagged location. I have tried merging the suggestions I've come across here on stack overflow, and have successfully gotten the users browser to center the map based off of geolocation, but whenever I try to add a marker outside of the standard var=locations, all of the markers disappear. I am providing my working code, which simply lacks the feature to add the "current location" marker. If anyone has any input, I'd be thrilled.
var map = null;
var markerArray = [];
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(40.746613, -73.990109),
mapTypeControl: false,
navigationControl: false,
streetViewControl: false,
zoomControl: false,
styles: [{featureType:"landscape",stylers:[{saturation:-100},{lightness:65},{visibility:"on"}]},{featureType:"poi",stylers:[{saturation:-100},{lightness:51},{visibility:"simplified"}]},{featureType:"road.highway",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"road.arterial",stylers:[{saturation:-100},{lightness:30},{visibility:"on"}]},{featureType:"road.local",stylers:[{saturation:-100},{lightness:40},{visibility:"on"}]},{featureType:"transit",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"administrative.province",stylers:[{visibility:"off"}]/**/},{featureType:"administrative.locality",stylers:[{visibility:"off"}]},{featureType:"administrative.neighborhood",stylers:[{visibility:"on"}]/**/},{featureType:"water",elementType:"labels",stylers:[{visibility:"on"},{lightness:-25},{saturation:-100}]},{featureType:"water",elementType:"geometry",stylers:[{hue:"#ffff00"},{lightness:-25},{saturation:-97}]}]
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var locations = [
['90 West Apartment', 40.709943, -74.014430, 7, 'images/pin2.png'],
['Caffe Vita', 40.719652, -73.988411, 6, 'images/pin1.png'],
['Croxleys Ale House', 40.722480, -73.983386, 5, 'images/pin1.png'],
['Grays Papaya', 40.778291, -73.981829, 4, 'images/pin2.png'],
['The Back Room', 40.718723, -73.986913, 3, 'images/pin1.png'],
['MUD Coffee', 40.729912, -73.990678, 2, 'images/pin1.png'],
['Nurse Bettie', 40.718820, -73.986863, 1, 'pin2.png']];
for (var i = 0; i < locations.length; i++) {
createMarker(new google.maps.LatLng(locations[i][1], locations[i][2]),locations[i][0], locations[i][3], locations[i][4]);
}
mc.addMarkers(markerArray, true);
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(latlng, myTitle, myNum, myIcon) {
var contentString = myTitle;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: myIcon,
zIndex: Math.round(latlng.lat() * -100000) << 5,
title: myTitle
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
markerArray.push(marker);
}
window.onload = initialize;
Let's try this.
Put this in your initialize(): navigator.geolocation.getCurrentPosition(showPosition);
Then define showPosition:
var showPosition = function (position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Do whatever you want with userLatLng.
var marker = new google.maps.Marker({
position: userLatLng,
title: 'Your Location',
map: map
});
}
This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Closed 8 years ago.
Like many other people I'm finding identical values within my info windows. Alas, I've been using other posts in an attempt to troubleshoot. No luck.
Issue: Each of my infowindows shows the same values. Sigh.
Any help would be appreciated.
var map;
function initialize() {
var markers = [];
var mapOptions = {
zoom: 4,
scrollwheel: false,
streetViewControl: true,
panControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
// position: google.maps.ControlPosition.LEFT_CENTER
},
center: new google.maps.LatLng(-25.898854, 134.091377)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
setMarkers(map, beaches);
infowindow = new google.maps.InfoWindow({
content: "Loading..."
});
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
//url: 'assets/img/icon_pin.png',
//size: new google.maps.Size(40, 52),
//origin: new google.maps.Point(0, 0),
//anchor: new google.maps.Point(26, 20)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
var beaches = [
['Auburn', -33.847113, 151.04485, 1, '100', 'Parramatta', 'Road', 'Auburn', 'NSW', '2144', '02 7837 9800', '06:00 - 22:00', '06:00 - 22:00'],
['Balgowlah Platinum', -33.79284, 151.26376, 2, 'Shop 67, 197-215', 'Condamine', 'Street', 'Balgowlah', 'NSW', '2093', '1300 55 77 99', '06:00 - 21:30', '06:00 - 21:30'],
['Bankstown', -33.931208, 151.02895, 3, 'Unit 1-2, 9', 'Chapel', 'Street', 'South Bankstown', 'NSW', '2200', '02 8707 4700', '06:00 - 22:00', '06:00 - 22:00']
['Bayside', -37.954768, 145.03128, 4, '241 - 245', 'Bay', 'Road', 'Highett', 'VIC', '3190', '03 9559 7400', '06:00 - 22:00', '06:00 - 22:00']
];
function setMarkers(map, locations) {
var image = {
url: 'assets/img/icon_pin.png',
size: new google.maps.Size(40, 52),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(26, 20)
};
var shape = {
coord: [1, 1, 1, 52, 40, 52, 40 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape
});
var contentString = '<div class="siteNotice"><h4>'+beach[0]+'</h4><p>'+beach[4]+' '+beach[5]+' '+beach[6]+' '+beach[7]+', '+beach[8]+', '+beach[9]+'</p><p><strong>Contact:</strong> '+beach[10]+'</p><p><strong>Opening Hours:</strong><br><span>Monday:</span> '+beach[11]+'<br><span>Tuesday:</span> '+beach[11]+'<br><span>Wednesday:</span> '+beach[11]+'<br><span>Thursday</span>: '+beach[11]+'<br><span>Friday:</span> '+beach[11]+'<br><span>Saturday</span>: '+beach[11]+'<br><span>Sunday:</span> '+beach[11]+'</p></div>';
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(contentString);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
I had to create an array of info markers to hold the data.
var markers = [];
function addMapLocation(map, lat, long, title, message) {
var locationLatLong = new google.maps.LatLng(lat, long);
var locationMarker = new google.maps.Marker({ position: locationLatLong, map: map, title: title.trim() });
attachMessage(locationMarker, message);
markers.push(locationMarker);
}
function attachMessage(marker, message) {
var locationInfo = new google.maps.InfoWindow({ content: message });
google.maps.event.addListener(marker, 'click', function () { locationInfo.open(marker.get('map'), marker); });
}