Google Maps API Implementing click event to get the target element - google-maps

Here's a question regarding Google maps API events:
marker.addListener('click', _.bind(function (e) {
}
In the above code I am unable to get e.target element on which I need to call a function.
Basically the situation is I have a list of markers and on click of one, the function needs to be triggered and on click of the same marker the function should unbind.
Can anyone help me with this?

Hello I worked with marker in past and kinda had same issue, I did some research and found this solution on SO and it worked.
you can created function like this
function createCallback(marker, callback) {
google.maps.event.addListener(marker, 'click', function () {
// do whatever you want to do
callback()
});
}
And after that call it like this
var markerPropertyLocation = new google.maps.Marker({
position: {markerPosition},
map : {map},
icon: new google.maps.MarkerImage(
{iconImage},
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(20, 27))
});
createCallback(markerPropertyLocation, function(){
// callback funcation
});
Thanks

To be more precise with my requirements, I have restructured my queries and reposting the same:
On our Google maps implementation we have the following Requirements:
• Getting the target element that is clicked marker, out of all displayed on the screen
• Enlarge the marker once clicked and apply class only to that specific marker(clicked marker)
We have written the following code, but it doesn’t give the above results.
However, a similar interaction works on hover showing the tootip with details
Code Snippet:
ReferenceMap.prototype.showPoint = function showPoint(point, map) {
var location = point.get('location')
, marker = new google.maps.Marker({
store_id: point.get('internalid')
, icon: iconSrc
, map: map
, point: point
, title: point.get('internalid')
});
allMarker.push(marker);
marker.setPosition(new google.maps.LatLng(location.latitude, location.longitude));
marker.setVisible(true);
marker.addListener('mouseover', _.bind(function () {
this.showInfoWindowOnClick(marker, map);
}, this));
marker.addListener('mouseout', _.bind(function () {
hideShowInfoWindow();
}, this));
marker.addListener('click', _.bind(function (e) {
// var markerTitle = marker.title;
// var markerID = marker.store_id;
// var target = markerTitle == markerID;
// if(target == e.target) {
// $('.marker img').css('width',200);
// dealerDetailsLeftBlock();
// }
// else {
// $('.marker img').removeAttr('style');
// }
console.log(e.target);
areaMarkers.reset();
for (var i = 0; i < allMarker.length; i++) {
allMarker[i
].isClicked = 'F';
allMarker[i
].point.set('isClicked', 'F');
marker.set('isClicked', 'T');
if (map.getBounds().contains(allMarker[i
].getPosition())) {
//console.log(allMarker[i]);
if (allMarker[i
].isClicked == 'T') {
$('[title="' + marker.title + '"
]').addClass('marker - design');
console.log($('[title="' + marker.title + '"
]'))
// console.log(allMarker[i]);
allMarker[i
].point.set('isClicked', 'T');
}
areaMarkers.add(allMarker[i
].point);
}
};
//console.log(areaMarkers);
dealerDetailsLeftBlock();
this.trigger('getSideBar')
}, this));
if (this.markerCluster) {
this.markerCluster.addMarker(marker);
}
return marker;
};

Related

Filter google markers with knockout

I've been trying to solve this issues with no luck. I already check other posts and no luck. I think I have an error on my code, my goal is to be able to filter the list and show/hide only the markers on that list. A sample of the code is here: https://jsfiddle.net/rp2t3gyn/2/
Here is a sample of the code that is not working for some reason:
self.filteredPlaces = ko.computed(function() {
var filter = self.filter().toLowerCase();
if (!filter) {
ko.utils.arrayForEach(self.placeList(), function (placeItem) {
placeItem.marker.setVisible(true);
});
return self.placeList();
} else {
return ko.utils.arrayFilter(self.placeList(), function(placeItem) {
// set all markers visible (false)
var result = (placeItem.city.toLowerCase().search(filter) >= 0);
placeItem.marker.setVisible(result);
return result;
});
}
}, this);
Thanks
In order to filter the markers you need to do a few things.
Your first problem is this line:
placeItem.marker.setVisible(true);
Place item doesn't have a marker object based on your constructor. So, you have to add it. I changed the Place constructor to add a marker object (see below).
var Place = function(data, map, viewmodel) {
this.city = data.city;
this.lat = data.lat;
this.lng = data.lng;
var marker = new google.maps.Marker({
map: map,
position: {lat: data.lat, lng: data.lng},
city: data.city,
icon: {
path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
scale: 5
},
animation: google.maps.Animation.DROP,
});
marker.addListener('click', function() {
viewmodel.clickSelection(marker, viewmodel.largeInfoWindow);
});
this.marker = marker;
};
and used that to initialize your objects. Lastly, I changed your filteredPlaces function, it needs to subscribe to the query observable so that when you type in text the markers on the map adjust accordingly .
self.query.subscribe(function() {
var filter = self.query().toLowerCase();
if (!filter) {
ko.utils.arrayForEach(self.placeList(), function (placeItem) {
placeItem.marker.setMap(map);
});
return self.placeList();
} else {
ko.utils.arrayForEach(self.placeList(), function(placeItem) {
var result = (placeItem.city.toLowerCase().search(filter) >= 0);
if(result)
placeItem.marker.setMap(map);
else
placeItem.marker.setMap(null);
});
}
});
Working fiddle here.

Google Nearby change type on click

I'm working on a project where I'd like to show the choosen event on google maps with some additional information. (ex. all gas stations radius 2km).
Google doesn't allow a nearby search with multiple types.
Restricts the results to places matching the specified type. Only one type may be specified (if more than one type is provided, all types following the first entry are ignored).
So for now I'd like to change the type (ex. gas_station or store) if I click to a custom button I added.
(used the google document example)
Screenshot: http://imgur.com/qYwLuw4
Question:
Which is the best way to change the type and refresh the map with the new information?
I'd like to present you our solution.
We wrote a clear() and a showType() function, which will erase all markers and let the right ones appear on click. By the way we give the button a state class called "selected" for CSS styling.
We didn't find a solution to show both (washstation AND fuelstation).
<script type="text/javascript">
var map;
var infowindow;
var service;
var eventLocation = {lat: <?= $arrCoordinates['latitude']?>, lng: <?= $arrCoordinates['longitude']?>};
var markers = [];
var wash = document.getElementById('wash'); //washbutton
var fuel = document.getElementById('fuel'); //fuelstation button
function initMap() {
map = new google.maps.Map(document.getElementById('eventmap'), {
center: eventLocation,
zoom: 13,
});
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
showType('gas_station');
fuel.classList.add("selected");
typeControl(map);
}
// Type control function
function typeControl ( map ) {
google.maps.event.addDomListener(fuel, 'click', function() {
wash.classList.remove("selected");
fuel.classList.remove("selected");
clear()
showType('gas_station')
this.classList.add("selected");
});
google.maps.event.addDomListener(wash, 'click', function() {
wash.classList.remove("selected");
fuel.classList.remove("selected");
clear()
showType('car_wash')
this.classList.add("selected");
});
}
function showType(type) {
service.nearbySearch({
location: eventLocation,
radius: 10000,
type: [type]
}, callback);
}
function clear() {
markers.forEach(marker => marker.setMap(null));
markers = [];
}
function callback(results, status) {
clear()
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
createTuningEventMarker();
}
}
function createTuningEventMarker(place) {
var eventLocation = {lat: <?= $arrCoordinates['latitude']?>, lng: <?= $arrCoordinates['longitude']?>};
var eventIcon = {
url: 'https://www.foo.lol/img/icons/pin.svg',
// This marker is 20 pixels wide by 32 pixels high.
scaledSize: new google.maps.Size(60, 60),
// The origin for this image is (0, 0).
origin: new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(30,60)
};
var marker = new google.maps.Marker({
map: map,
icon:eventIcon,
position: eventLocation
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<?= $event['name']?>');
infowindow.open(map, this);
});
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name + "<br>Adress: " + place.vicinity);
infowindow.open(map, this);
});
}
</script>

javascript - Add text to gmap marker

I use gmap for geolocation, i.e. to set markers on a google map on specific positions.
Now what I want to achieve is to set markers and as soon as a user clicks on one of these markers, a info window opens and shows specific text. Every marker has its own text.
Now the problem is that I can't determine which marker the user has clicked and therefore can't set the right text.
Here's a code snippet:
//**Global variables**/
var thingsOfInterest = new Array(new Array(), new Array(),new Array());
var map = null;
//End Global variables
//init google map
function initGoogleMaps(){
map = new google.maps.Map(document.getElementById("map_canvas"));
var centerMap = new google.maps.LatLng(48.337881,14.320323);
$('#map_canvas').gmap({'zoom':7,'center': centerMap});
$('#map_canvas').gmap('option', 'zoom', 10);
//This is not working on my ios-simulator, no idea why. Anyway....
forge.geolocation.getCurrentPosition(function(position) {
alert("Your current position is: "+position);
}, function(error) {
});
}
/*End init map*/
/*Set the markers on the map*/
function setMarkers() {
/* thingsOf Interest contains:
* thingsOfInterest[i][0] -> the text that the marker should hold
* thingsOfInterest[i][1] -> the latitude
* thingsOfInterest[i][2] -> the longitude
*/
for (var i = 0; i < thingsOfInterest.length; i++) { //Iterate through all things
var item = thingsOfInterest[i]; //get thing out of array
var itemLatLng = new google.maps.LatLng(item[1], item[2]);
$('#map_canvas').gmap('addMarker', {'position': new google.maps.LatLng(item[1],item[2]) } ).click(function(e) {
$('#map_canvas').gmap('openInfoWindow', {'content': 'dummyContent'}, this); ///////SET REAL CONTENT HERE
});
}
}
Now this works all great, but what I miss is to get the marker the user has clicked on in the function()-eventHandler. If I could get the specific marker, I could set the text on it.
I hope this is clear enough.
Any help is very appreciated.
Thanks,
enne
Assuming your code with dummy text is working, you can pass your text right away..
$('#map_canvas').gmap('addMarker', {'position': new google.maps.LatLng(item[1],item[2])})
.click(function(e) {
$('#map_canvas').gmap('openInfoWindow', {'content': item[0]}, this);
});
Or another approach would be:
function setMarkers() {
for (var i = 0; i < thingsOfInterest.length; i++) {
var item = thingsOfInterest[i];
var itemLatLng = new google.maps.LatLng(item[1], item[2]);
var marker = new google.maps.Marker({ position: itemLatLng, map: map });
google.maps.event.addListener(marker, 'click', function () {
var infowindow = new google.maps.InfoWindow({ content: item[0] });
infowindow.open(map, marker);
});
}
}

How to tell if a Google Map Marker is currently selected?

I have a simple enough map on Google Maps V3.
I change the icon image on mouse over listener event, I change it back on mouse out simple enough.
I change the icon again when I click the marker, but, I want to keep that icon while the marker is selected. When I mouse out, the marker icon changes again because I told it to do so in the mouse out listener event.
I need to exclude the selected marker from the mouseout listener event but I can't figure out how to find the marker I have currently selected. Any ideas?
Here is my code
google.maps.event.addListener(marker, 'mouseover', function () {
this.setIcon("images/star-3-white.png");
});
google.maps.event.addListener(marker, 'mouseout', function () {
// this overwrites the image again,
// need to exclude the current one here
this.setIcon("images/star-3.png");
});
google.maps.event.addListener(marker, 'click', function () {
this.setIcon("images/star-3-white.png");
infowindow.setContent(this.html);
infowindow.open(map, this);
});
Either
create a member of the marker .selected and set that when you click on it, then test it in the mouseout function (and the mouseover function if you want to be complete), don't change the icon if it is set.
create a global variable (assuming there is only one marker selected at a time), set that equal to the marker that was clicked. In the mouseout (and mouseover) check if it is equal to the current marker (this), if it is don't change the icon.
A bit long winded but I just added a variable to store the current marker title which I know is unique. I then check to see if it is that one that I am selecting. Also, I make sure to reset all the markers so it doesnt stay the same color as a selected one:
var clickedMarkerTitle = null;
function addMarker(latLng, _title, contentString) {
marker = new google.maps.Marker({
map: map,
position: latLng,
icon: "images/star-3.png",
title: _title,
html: contentString
});
google.maps.event.addListener(marker, 'mouseover', function () {
this.setIcon("images/star-3-white.png");
});
google.maps.event.addListener(marker, 'mouseout', function () {
//this.setIcon("images/star-3.png");
testIcon(this);
});
google.maps.event.addListener(marker, 'click', function () {
resetMarkerIcons();
saveIconState(this);
this.setIcon("images/star-3-white.png");
infowindow.setContent(this.html);
infowindow.open(map, this);
});
markersArray.push(marker);
}
function resetMarkerIcons() {
// reset all the icons back to normal except the one you clicked
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setIcon("images/star-3.png");
}
}
function saveIconState(marker) {
clickedMarkerTitle = marker.title;
}
function testIcon(marker) {
$('#test').html('<span>' + marker.title + '</span>');
if (clickedMarkerTitle != null) {
$('#test').html('<span>' + marker.title + ' and its not null</span>');
if (marker.title != clickedMarkerTitle) {
$('#test').html('<span>' + marker.title + ' and ' + clickedMarkerTitle + '</span>');
marker.setIcon("images/star-3.png");
}
}
else {
marker.setIcon("images/star-3.png");
}
}
Stumbled on this answer when searching for something else. This will do.
var currentMarker = null;
var markerIcon = 'some.svg';
var markerIconHover = 'some-other.svg';
// Initialize marker here
[...]
// Set current marker on click
google.maps.event.addListener(marker, 'click', function() {
// Reset market icons
clearMarkerIcons();
// Set hovered map marker
marker.setIcon(markerIconHover);
// Set current marker
currentMarker = marker;
// Open infoWindow here
[...]
});
// Set correct icon on mouseover
google.maps.event.addListener(marker, 'mouseover', function() {
marker.setIcon(markerIconHover);
});
// Set correct icon on mouseout
google.maps.event.addListener(marker, 'mouseout', function() {
if (currentMarker !== marker) {
marker.setIcon(markerIcon);
}
});
// Clear all set marker icons
function clearMarkerIcons() {
for (var i = 0; i < map.markers.length; i++) {
map.markers[i].setIcon(markerIcon);
}
}

changing z index of marker on hover to make it visible

I'm trying to make the marker i'm currently hovering on have a greater z-index than the others, so that even if it's hidden by other markers it'll gain full visibility when I hover on it.
On click of any marker i want to do the same .
google.maps.event.addListener(this.marker, 'mouseover', function() {
this.old_ZIndex = this.getZIndex(); //trying to get the current z- index
console.log(this.old_ZIndex); //this is undefined: why?
this.setZIndex(this.old_ZIndex + 100); //setting a higher z-index than all other markers
console.log("the old z index is ",this.old_ZIndex);
});
But with this i would be infinitely increase the z index .. is there some other way in which I can have the to revert back when i hover or click any other marker . .
Or is there any better way to implement it ??
'this.getZIndex()' always returns 'undefined' if you haven't previously set a zIndex on the marker, either when initialising it in the first place or by using the setOption() function.
Your script may also not work 100% if there are more than 100 markers.
I've put together a very simple map below that contains 2 markers, slightly overlapping. On hover of one of the markers it will set the zIndex to the highest needed to bring it to the top, then return it back to what it was previously on mouseout:
var map;
var markers = new Array();
var highestZIndex = 0;
function initialize() {
/* SETUP MAP */
var myLatlng = new google.maps.LatLng(52.06768, -1.33758);
var mapOptions = {
center: myLatlng,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
/* ADD 1st MARKER */
var markerOptions = {
position: new google.maps.LatLng(52.06768, -1.32058),
map: map,
zIndex:1
};
marker = createMarker(markerOptions, false);
marker.set("myZIndex", marker.getZIndex());
google.maps.event.addListener(marker, "mouseover", function() {
getHighestZIndex();
this.setOptions({zIndex:highestZIndex+1});
});
google.maps.event.addListener(marker, "mouseout", function() {
this.setOptions({zIndex:this.get("myZIndex")});
});
/* ADD 2nd MARKER */
var markerOptions = {
position: new google.maps.LatLng(52.06768, -1.33758),
map: map,
zIndex:2
};
marker = createMarker(markerOptions, false);
marker.set("myZIndex", marker.getZIndex());
google.maps.event.addListener(marker, "mouseover", function() {
getHighestZIndex();
this.setOptions({zIndex:highestZIndex+1});
});
google.maps.event.addListener(marker, "mouseout", function() {
this.setOptions({zIndex:this.get("myZIndex")});
});
}
function createMarker(markerOptions) {
var marker = new google.maps.Marker(markerOptions);
markers.push(marker);
return marker;
}
function getHighestZIndex() {
// if we haven't previously got the highest zIndex
// save it as no need to do it multiple times
if (highestZIndex==0) {
if (markers.length>0) {
for (var i=0; i<markers.length; i++) {
tempZIndex = markers[i].getZIndex();
if (tempZIndex>highestZIndex) {
highestZIndex = tempZIndex;
}
}
}
}
return highestZIndex;
}
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
zIndex: 1
});
google.maps.event.addListener(marker, 'mouseover', function () {
this.setOptions({zIndex:10});
});
google.maps.event.addListener(marker, 'mouseout', function () {
this.setOptions({zIndex:1});
});
I think the easiest way is to use CSS instead of Javascript:
.your-custom-marker-class {
z-index: 100;
}
.your-custom-marker-class:hover {
z-index: 101;
}
This does mean you have to use CustomOverlays (https://developers.google.com/maps/documentation/javascript/customoverlays#introduction) instead of default markers, but that has some other advantages too, if you want to customize layout, etc.
So this question was a year ago but I figured something out and thought others might appreciate it. There's even icon rollovers involved as a bonus. I'm dealing with thousands of bus and train stops being shown so this turned out to be pretty efficient for me.
google.maps.event.addListener(marker, 'mouseover', function () {
if (this.getIcon() === busnot) { this.setIcon(busovr); }
if (this.getIcon() === lrtnot) { this.setIcon(lrtovr); }
$.each($.grep(markers, function (item) { return item.getZIndex() == 10 }), function (i, e) { e.setOptions({ zIndex: 1 }); });
this.setOptions({zIndex:10});
});
google.maps.event.addListener(marker, 'mousemove', function () {
if (this.getIcon() === busnot) { this.setIcon(busovr); }
if (this.getIcon() === lrtnot) { this.setIcon(lrtovr); }
$.each($.grep(markers, function (item) { return item.getZIndex() == 10 }), function (i, e) { e.setOptions({ zIndex: 1 }); });
this.setOptions({ zIndex: 10 });
});
google.maps.event.addListener(marker, 'mouseout', function () {
if (this.getIcon() === busovr) { this.setIcon(busnot); }
if (this.getIcon() === lrtovr) { this.setIcon(lrtnot); }
$.each($.grep(markers, function (item) { return item.getZIndex() == 10 }), function (i, e) { e.setOptions({ zIndex: 1 }); });
});
The way I did it was to have one variable(highestZ) set the zIndex for all my markers(in my case i did it with polylines) and increments, and one variable to temporarily hold the z-index of whichever marker i "mouseover" on:
Set the variables as global:
var highestZ = 1; //set 1 for the first z-index
var tmpZIndex = 0;
Then when building/initializing your marker options just add this
zIndex : highestZ++ //this sets the z-index for the marker and increments it for the next one
Sample (i did mine in a loop) :
var routePath = new google.maps.Polyline({
strokeWeight: 5,
zIndex : highestZ++ //set zIndex and increment it
});
And finally just do mouseover and mouseout event handlers like this:
google.maps.event.addListener(routePath, "mouseover", function() {
tempZIndex = routePath.zIndex; //set "this" z-index value to tempZIndex for mouseout
routePath.setOptions({
zIndex: highestZ + 1 //set the z-index to the highest z-index available plus 1 for it to be the topmost marker on mouseover
});
});
google.maps.event.addListener(routePath, "mouseout", function() {
routePath.setOptions({
zIndex: tempZIndex //set the z-index back to it's original set upon mouseover earlier
});
My answer is probably simple, and general and of course incomplete to focus on the problem only, hopefully you can work it further to fit your project.