This question already has answers here:
Have just one InfoWindow open in Google Maps API v3
(12 answers)
Closed 5 years ago.
when opening another infowindow the previous ones remain open.
How to automatically close the previous information window if I open another information window? I am something new, can you help me
var map;
var markers = [];
function initMap() {
var cucuta = {lat: 7.9145395, lng: -72.505966};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: cucuta,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
#foreach($users as $user)
var ubicaciones = {lat: {{ $user->latitud }}, lng: {{ $user->longitud }} };
var titulo = '{{ $user->name }}';
addMarker(ubicaciones, titulo);
#endforeach
}
function addMarker(location, titulo) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location),
map: map,
title: titulo
});
markers.push(marker);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker) {
return function() {
infowindow.setContent(titulo);
infowindow.open(map, marker);
}
})(marker));
}
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function showMarkers() {
setMapOnAll(map);
}
I've just tried this in tryit, and it works as expected :
var map;
var infowindow;
function initMap() {
infowindow = new google.maps.InfoWindow();
var cucuta = {lat: 7.9145395, lng: -72.505966};
map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 14,
center: cucuta,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
addMarker({lat: 7.9145395, lng: -72.505966}, 'This is the info of <br>MAP1');
addMarker({lat: 7.9045395, lng: -72.505966}, 'This is the info of <br>MAP2');
}
function addMarker(location, titulo) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location),
map: map,
title: titulo
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(titulo);
infowindow.open(map, marker);
});
}
Related
I got an existing map on my page with markers generated by PHP from a database. Works fine. Now I would like to add a new marker in this map.
I can't get it working:
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map;
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.2193835,6.5665018),
zoom: 10,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("geo.php?gmt=<? echo $stringGMT;?>&cat=<? echo $stringAAN;?>&abo=<? echo $stringABO;?>", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var markersskg=[];
create markers code: working
var icon = customIcons["bar"] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
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);
});
}
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, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
function addmarker(lat,lon) {
var myLatLng = {lat: lat, lng: lon};
var marker;
//create a marker
marker = new google.maps.Marker({
position: myLatLng,
map: map,
draggable: true
});
}
and the onclick to call:
<div id="map" style="width: 100%; height: 600px"></div>
<button id="button" onClick="addmarker(53.0241066,6.571086);">Drop Markers</button>
You declare var map in load function and then is not visible in addMarker function
try declaring var map in global scope
var map ;
var customIcons = {
skg: {
icon: 'http://mywebsite.nl/img/logo_transparant24.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(53.2193835,6.5665018),
zoom: 10,
mapTypeId: 'roadmap'
});
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
});
}
I have a little function that adds a marker and info window when it is clicked. However, when I click on a new location, the old one remains. I'd like it to be replaced by the new one. Here is my code:
function MapInitialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(43,-77),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
var marker = new google.maps.Marker({
position: event.latLng,
map: map
})
var infowindow = new google.maps.InfoWindow({
content: 'Content Here'
});
infowindow.open(map,marker);
});
}
Thanks!
Delete the old marker before creating the new one:
var marker = null;
function MapInitialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(43,-77),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
position: event.latLng,
map: map
})
var infowindow = new google.maps.InfoWindow({
content: 'Content Here'
});
infowindow.open(map,marker);
});
}
I'm trying to adapt my code with json in google maps. I tried looking at other threads of stackoverflow but did not help me.
How do I show multiple points on the map with the coordinates that are received by json?
This code in firebug shows no errors and the map appears all blue.
var geocoder;
var map;
function initialize() {
var url = '/project/display/get_coordinates/';
$.getJSON(url, function(data) {
$.each(data, function(index, c) {
//alert(c.fields['lat']+','+c.fields['lng']); result: -23.0522826,-43.32745712
//Map
latlng = new google.maps.LatLng(c.fields['lat']+','+c.fields['lng']);
//options
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: true
};
//get the map
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//marker
var marker = new google.maps.Marker({
map: map,
position: latlng,
//title: {{i.display.codigo}}
});
//infowindow
var infowindow = new google.maps.InfoWindow({
content: 'oi'
});
//click infowindow
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});//close each
});//close getjson
}//close initialize
My response in Json:
[{"pk": 1, "model": "address.coordinates", "fields": {"lat": "-23.0522826", "lng": "-43.32745712"}}, {"pk": 2, "model": "address.coordinates", "fields": {"lat": "-22.24569326", "lng": "-43.7028948"}}]
Thanks!
You have 1 real error here:
latlng = new google.maps.LatLng(c.fields['lat']+','+c.fields['lng']);
google.maps.LatLng expects 2 parameters(lat &lng) , but you provide 1(a string containing lat and lng, joined by a comma) . It has to be
latlng = new google.maps.LatLng(c.fields['lat'],c.fields['lng']);
But you also have a logical error:
You overwrite the last map created on every each-loop
Create the map and the infoWindow outside of the $.each()
function initialize()
{
var myOptions =
{
zoom: 5,
center: new google.maps.LatLng(1,1) ,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: true
};
var url = '/project/display/get_coordinates/';
$.getJSON(url, function(data) {
map= new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds=new google.maps.LatLngBounds();
infowindow = new google.maps.InfoWindow({
content: 'oi'
});
$.each(data, function(index, c) {
var latlng = new google.maps.LatLng(c.fields['lat'],c.fields['lng']);
var marker = new google.maps.Marker({
map: map,
position: latlng,
title:'pk:'+c.pk
});
bounds.extend(latlng);
google.maps.event.addListener(marker, 'click', function() {
infowindow.close();
infowindow.setContent('pk:'+c.pk);
infowindow.open(map, marker);
});
});//close each
map.fitBounds(bounds);
});//close getjson
}//close initialize