for(i = 0; i < locations.length; i++) {
currentLocation = locations[i];
var mapMarker = new google.maps.Marker ({
position: locations[i][0],
map: map,
label: labels[i],
title: locations[i][1],
zoom: 18
})
mapMarkers.push(mapMarker);
mapMarkers[i].addListener('click', markerClick(currentLocation));
}
function markerClick(location) {
console.log("you clicked " + location)
}
The function markerClick is being called each time it is added to an element. How can i make it so it is only called when the element is clicked? i read in another answer herethat leaving out the () would fix this, but I need to pass a paramater and am not sure how to do this. thanks for any help
One option would be for your markerClick function to return a function.
function markerClick(location) {
return function(evt) {
console.log("you clicked " + JSON.stringify(location));
}
}
proof of concept fiddle
code snippet:
var locations = [
[{lat: 42, lng: -72}, "Here"],
[{lat: 42.1,lng: -72.1}, "There"]
];
var mapMarkers = [];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(42, -72),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (i = 0; i < locations.length; i++) {
currentLocation = locations[i];
var mapMarker = new google.maps.Marker({
position: locations[i][0],
map: map,
// label: labels[i],
title: locations[i][1],
zoom: 18
})
mapMarkers.push(mapMarker);
mapMarkers[i].addListener('click', markerClick(currentLocation));
}
}
function markerClick(location) {
return function(evt) {
console.log("you clicked " + JSON.stringify(location));
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
When you add the listener, you're calling the markerClick() function rather passing it as a variable. Here's how to fix it:
//using a separate function like this avoids some nasty
//problems with callbacks and closures in for loops
function addMapMarkerClickListener( mapMarker, location ) {
//we use an anonymous function as the listener
mapMarker.addListener('click', function() {
markerClick( location );
});
}
for(i = 0; i < locations.length; i++) {
currentLocation = locations[i];
var mapMarker = new google.maps.Marker ({
position: locations[i][0],
map: map,
label: labels[i],
title: locations[i][1],
zoom: 18
})
mapMarkers.push(mapMarker);
addMapMarkerClickListener( mapMarkers[i], currentLocation );
}
function markerClick(location) {
console.log("you clicked " + location)
}
Related
The markers in my program just wont remove with the deleteMarkers() function
CSS:
#map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
HTML:
<div style="height:500px; width:750px;">
<div id="map-canvas"></div>
</div>
<select class="form-control" name="dateSelect" id="dateSelect" onchange="dateSelect_Event();"></select>
Javascript:
var map; <--- global variables
var locations = [];
var lat_get = '';
var long_get = '';
var marker=[];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {lat: 7.072617, lng: 125.599494},
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 13,
});
};
function deleteMarkers() {
for (var i = 0; i < marker.length; i++ ) {
marker[i].setMap(null);
}
marker.length = 0;
}
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.setMap(map);
});
}
Firebase:
-databaseName
--location
---latitude
---longitude
I just use firebase to get the lat and long on every change of the html select option and it work perfectly. The problem this time is it can't delete the markers. Should I do the deleteMarkers differently?
Thanks to #StackSlave's answer. I was able to successfully remove it by creating and pushing the google_marker to the global marker variable.
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
var google_marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
google_marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.push(google_marker);
});
marker.setMap(map);
}
I want to reload map in ajax call.This code is reloading whole page when i change status it reloads whole page.I want after 10 seconds only map reloads not whole page. if i select on change available then map reloads after every 10 seconds in available option.
i have drivers if i select status of driver available then map shows the drivers which are available. i want to refresh map after 10 sec so that i can see if there is any other driver available. if available then it will show on map without reloading whole page. This is what i want.
i am refreshing content in some div of the page by using jQuery load() function but its not working.
Html:
<div class="row">
<div class="col-md-12">
<div id="map" style="height: 550px;">
<div id="time">
<?php echo date('H:i:s');?>
</div>
</div>
</div>
</div>
Script:
$('#status').change(function () {
var job_status = $(this).val();
$.ajax({
url: '{{ URL::to('/get_drivers/')}}' + '/' + $(this).val(),
type: 'get',
datatype: 'json',
success: function (response) {
setInterval("my_function();", 10000);
function my_function() {
$('#map').load(location.href + ' #time');
}
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 31.5204, lng: 74.3587},
mapTypeId: 'roadmap'
});
var infowindow = new google.maps.InfoWindow({});
var marker, i;
{{--var carIcon = '{{asset('images/red-car.png')}}';--}}
if (gmarkers.length > 0) {
for (i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].getMap() != null) {
gmarkers[i].setMap(null);
} else {
gmarkers[i].getMap();
gmarkers[i].setMap(map);
}
}
gmarkers = [];
}
for (i = 0; i < locationData.length; i++) {
if (job_status == 8) {
if (job_status === '') {
gmarkers = [];
}
else {
for (i = 0; i < locationData2.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locationData2[i]['driver_lat'], locationData2[i]['driver_long']),
map: map,
optimized: false,
icon: '{{asset('images/grey-car.png')}}'
});
google.maps.event.addListener(marker, 'mouseover', (function (marker, i) {
return function () {
infowindow.setContent('<h6><b>' + locationData2[i]['first_name'] + '</h6>');
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addListener(map, 'click', (function (marker, i) {
return function () {
infowindow.setContent();
infowindow.close(marker);
}
})(marker, i));
// Push your newly created marker into the array:
gmarkers.push(marker);
var myoverlay = new google.maps.OverlayView();
myoverlay.draw = function () {
// add an id to the layer that includes all the markers so you can use it in CSS
this.getPanes().markerLayer.id = 'markerLayer';
};
myoverlay.setMap(map);
}
}
}
});
You do not need to renew the whole map but drivers markers only (or to be even more precise - not whole markers but their positions only)
I use google own example and put there couple of markers which positions get renewed to random location every second.
//random locations
var latArr = [-20.363882, -21.363882, -22.363882, -23.363882, -24.363882, -25.363882, -26.363882, -27.363882, -28.363882, -29.363882];
var lngArr = [125.044922, 126.044922, 127.044922, 128.044922, 129.044922, 130.044922, 131.044922, 132.044922, 133.044922, 134.044922];
//global array to hold all markers
var markersArr = [];
//map init from google example
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -25.363882, lng: 131.044922}
});
//create markers
var marker1 = new google.maps.Marker({
position: map.getCenter(),
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
},
draggable: true,
map: map
});
var marker2 = new google.maps.Marker({
position: map.getCenter(),
icon: {
path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
scale: 5
},
draggable: true,
map: map
});
markersArr.push(marker1);
markersArr.push(marker2);
}
//function to change markers locations
function renewMarkers(){
for(i=0; i<markersArr.length; i++){
var lt = Math.floor(Math.random()*10);
var ln = Math.floor(Math.random()*10);
markersArr[i].setPosition({lat: latArr[lt], lng: lngArr[ln]})
}
}
setInterval(renewMarkers, 1000);
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
<div id="map"></div>
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>
I want to hide specific infoWindow content among multiple infowindows in google maps. If I open single infowindow it is working fine, but If I open multiple infowindows at a time content gets changed in the another infowindow.
Please find below code
var map;
var markers = [];
function initMap() {
map = new
google.maps.Map(document.getElementById('map_canvas'), {
zoom: 14,
center: new google.maps.LatLng(13.018057, 77.666794),
mapTypeId: 'roadmap',
disableDefaultUI: true
});
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
map: map,
type: feature.type,
id:feature.id,
description: feature.description,
infoWindow:new google.maps.InfoWindow({})
});
marker.addListener('click', function() {
var content="<h5>"+marker.type+"</h5>"+
"<p id='des'>"+marker.description+"</p>"
google.maps.event.addListener(this.infoWindow,
'domready', function () {
if(marker.id===1){
document.getElementById("des").style.display="none";
}
});
this.infoWindow.setContent(content);
this.infoWindow.open(map,marker);
});
markers.push(marker);
}
var features = [
{
position: new google.maps.LatLng(13.018057, 77.666794),
type: 'type1',
id: 1,
description: 'welcome to Hyd'
}, {
position: new google.maps.LatLng(13.015136, 77.647265),
type: 'type2',
id:2,
description: ' welcome to Blr'
}, {
position: new google.maps.LatLng(13.009970, 77.660088),
type: 'type3',
id:3,
description: ' welcome to Mum'
}
];
for (var i = 0; i < features.length; i++) {
addMarker(features[i]);
}
}
$(document).ready(function() {
initMap();
});
Please find below
jsfiddle
Simplest fix is to use this inside the marker click event listener function to refer to the marker (the marker variable is left pointing to the last marker processed in the loop), then for the domready callback you need to save it (as that, in the callback function's closure)
Also, you have multiple infowindows with the same element id in them, element ids have to be unique. One option is to append the marker id to the element id (i.e. des1 for marker/infowindow 1).
marker.addListener('click', function() {
// save this for use inside domready event listener callback function
var that = this;
var content = "<h5>" + this.type + "</h5>" +
"<p id='des"+this.id+"'>" + this.description + "</p>"
// if need to wait for infowindow to open
google.maps.event.addListener(this.infoWindow, 'domready', function() {
console.log("that.id="+that.id)
if (that.id === 1) {
if (!!document.getElementById("des"+that.id))
document.getElementById("des"+that.id).style.display = "none";
}
});
this.infoWindow.setContent(content);
this.infoWindow.open(map, this);
// if domready has already fired
if (that.id === 1) {
if (!!document.getElementById("des"+that.id))
document.getElementById("des"+that.id).style.display = "none";
}
});
updated fiddle
code snippet:
var map;
var markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 14,
center: new google.maps.LatLng(13.018057, 77.666794),
mapTypeId: 'roadmap',
disableDefaultUI: true
});
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
map: map,
type: feature.type,
id: feature.id,
title: "" + feature.id,
description: feature.description,
infoWindow: new google.maps.InfoWindow({})
});
marker.addListener('click', function() {
// save this for use inside domready event listener callback function
var that = this;
var content = "<h5>" + this.type + "</h5>" +
"<p id='des" + this.id + "'>" + this.description + "</p>"
// if need to wait for infowindow to open
google.maps.event.addListener(this.infoWindow, 'domready', function() {
console.log("that.id=" + that.id)
if (that.id === 1) {
if (!!document.getElementById("des" + that.id))
document.getElementById("des" + that.id).style.display = "none";
}
});
this.infoWindow.setContent(content);
this.infoWindow.open(map, this);
// if domready has already fired
if (that.id === 1) {
if (!!document.getElementById("des" + that.id))
document.getElementById("des" + that.id).style.display = "none";
}
});
markers.push(marker);
}
var features = [
{
position: new google.maps.LatLng(13.018057, 77.666794),
type: 'type1',
id: 1,
description: 'welcome to Hyd'
}, {
position: new google.maps.LatLng(13.015136, 77.647265),
type: 'type2',
id: 2,
description: ' welcome to Blr'
}, {
position: new google.maps.LatLng(13.009970, 77.660088),
type: 'type3',
id: 3,
description: ' welcome to Mum'
}
];
for (var i = 0; i < features.length; i++) {
addMarker(features[i]);
}
}
$(document).ready(function() {
initMap();
});
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
i use code in this example
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: { lat: 35.687719, lng: 139.702146 }
});
map.addListener('click', function(e) {
window.event = e;
placeMarkerAndPanTo(e.latLng, map);
});
}
function placeMarkerAndPanTo(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
map.panTo(latLng);
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<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=AIzaSyDwqIkJwBb6g4KirOaLnNgE1I6MtWnKxac&callback=initMap&language=ja">
</script>
Now, i want to show only one point in map by lng, lat.
And when i click one new point in map, i want to remove marker for old point in map to ensure only show one point.
Can you help me.
Thanks
var map;
var gmarkers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: { lat: 35.687719, lng: 139.702146 }
});
map.addListener('click', function(e) {
removeMarkers();
window.event = e;
placeMarkerAndPanTo(e.latLng, map);
});
}
function placeMarkerAndPanTo(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
map.panTo(latLng);
gmarkers.push(marker);
}
function removeMarkers() {
for (i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<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=AIzaSyDwqIkJwBb6g4KirOaLnNgE1I6MtWnKxac&callback=initMap&language=ja">
</script>