Google maps event - get parent of clicked element - javascript

I have function with which I'm making new object 'claster'. In every claster is marker from google maps API. I want to click on this marker and get access to claster.icons[]. I'm binding click event in my function declaration. How to do it?
CODE
function newClaster(_center){
this.centerIco = _center;
this.center = this.centerIco.getPosition();
this.icons = [];
this.icons.push(this.centerIco);
this.addIcon = function(_icon){this.icons.push(_icon)};
this.marker = new google.maps.Marker({
position : this.center,
icon : {
url : 'map/circle.png',
scaledSize : new google.maps.Size(40,40),
size : new google.maps.Size(40,40),
},
map:map,
});
this.setCenter = function(ctr){
this.centerIco = ctr;
this.center = ctr.getPosition();
}
this.findCenter = function(){
this.centerIco = this.icons[parseInt((this.icons.length)%2)];
this.center = this.centerIco.getPosition();
}
google.maps.event.addListener(this.marker, 'click', function(){
this.icons
});
}
I'm binding click on marker.

add a function and send the marker to it on click, then you can get the icons by accessing the marker object:
google.maps.event.addListener(this.marker, 'click', getIcons(this));
function getIcons(marker){
console.log(marker.icons);
}

Related

How to show pushpin when double click?

I want to show pushpin when double click in map but pushpin not show. Thanks a lot.
Source code :
var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),
{ credentials: "Key", center: new Microsoft.Maps.Location(-00,00)zoom: 10 });
//add pushpin
var map = new Microsoft.Maps.Map($map.get(0), mapSettings);
Microsoft.Maps.Events.addHandler(map, 'doubleclick', function (e) {
var latitude = "";
var longitude = "";
var location = new Microsoft.Maps.Location(latitude, longitude);
var pushpin = new Microsoft.Maps.Pushpin(location, {'draggable': false });
map.entities.push(pushpin);
// Update destination count
$('#destinations-count').html(nodes.length);
});
To bind the double click on the Map Control of Bing Maps AJAX v7, you need to use the appropriate event which is dblclick.
Microsoft.Maps.Events.addHandler(map, 'dblclick', yourMethod);
Or inline:
Microsoft.Maps.Events.addHandler(map, 'click', function(e) { ... });
See the documentation on the MSDN here:
https://msdn.microsoft.com/en-us/library/gg427609.aspx

google maps infowindow shows first infowindow only even for other markers

I've seen other questions related to this and none of the solutions I saw seemed to help. Maybe I'm just overlooking something.
Any help would be appreciated.
I have a map that I'm loading upwards of 1000 markers. When a user performs a mouseover on the marker, I need the infowindow to display for that marker where the marker is.
The issue I'm having is that the same infowindow appears over the same marker no matter which marker I mouseover.
I provided a screenshot below that shows the map with the markers and an infowindow. So, no matter which marker I mouseover, that same infowindow is shown.
This is the code (gm is an instantiated google.maps object):
for (var i = 0; i < opts.LocationsData.length; i ++) {
var datum = opts.LocationsData[i];
var icon = new gm.MarkerImage(datum.map_pin_loc + datum.map_marker + '.svg',null, null, null, new google.maps.Size(31,51));
var loc = new gm.LatLng(datum.latitude, datum.longitude);
var zi = 500;
if(i>9)
{
datum.map_pin_icon = datum.map_pin_loc + 'dot1.svg';
icon = new gm.MarkerImage(datum.map_pin_icon,null, null, null, new google.maps.Size(8,8));
zi=450;
}
var marker = new gm.Marker({
position: loc,
/** title: datum.title != '' ? datum.title : datum.description, **/
icon: icon,
zIndex: zi,
map: map
});
marker.type = 'point';
marker.post_id = datum.pin_id;
marker.scrollAndAnimate = true;
/** (these are used elsewhere in my code for marker management and other purposes) **/
markers.push(marker);
markersLatLngObjs.push(loc);
var infowindow = new gm.InfoWindow({
content: '<strong>' + (datum.title != '' ? datum.title : datum.description) + '</strong>'
});
gm.event.addListener(marker, 'mouseover', function() {
infowindow.open(map,marker);
});
}
The pb is that the mouseover event handler is a closure referencing variables which are unique in the context of the calling function. Better move this part outside the loop to see clearer.
For example you can define a function such as :
function showInfo() {
// called in the context of a marker
var datum = opts.LocationsData[this.placeIndex];
var infowindow = new gm.InfoWindow({
content: '<strong>' + (datum.title != '' ? datum.title : datum.description) + '</strong>'
});
infowindow.open(map, this);
}
just before your loop, then tag the markers with a property placeIndex (for example) in your loop :
marker.placeIndex = i;
and finally bind the handler with :
gm.event.addListener(marker, 'mouseover', showInfo);
Edit: oops, my bad, forgot about the other references, same pb. You can probably replace the marker by 'this' within the handler. I updated the code.

Google Maps API v.3 Clearing and adding markers on marker click

I am pulling markers from a MySQL database table of locations, which uses a nested set model for hierarchical categorization.
That part is working well.
I can place all markers on the map, using MarkerManager to show/hide at different zoom levels (using the 'depth' field from my table). That works nicely.
My issue is that if a marker for a country is clicked on, I would like all markers outside that country to be removed. Getting a single country's markers is trivial, I just feed a parent id to the xhr function. But clearing the markers... this is stumping me. I've been working at it for days, and just can't seem to make headway.
Here is the business-end of the JS
var map = new google.maps.Map(document.getElementById('gMap'), mapOptions);
// init the markerManager
var mgr = new MarkerManager(map);
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('Dark', darkMap);
map.mapTypes.set('Light', lightMap);
map.setMapTypeId('Dark');
// lat lng bounds for center/zoom marker
var bounds = new google.maps.LatLngBounds();
// infowindow (infobox)
// init here, and re-use
var ib = new InfoBox();
var oldDraw = ib.draw;
ib.draw = function() {
oldDraw.apply(this);
jQuery(ib.div_).hide();
jQuery(ib.div_).fadeIn('slow');
}
// init marker list
// for removing 'old' markers and loading new ones
var markersArray= [];
// load markers from database
function loadMarkers(params) {
var params = params || {};
var pid = params.pid || 5;
deleteOverlays(pid,function(){
// alert("deleteOverlays(" + pid + ");")
$.getJSON('/map/xhr_get_descendants', {
pid : pid
}, function(data) {
var bounds = new google.maps.LatLngBounds();
$.each(data, function(key, val) {
if (val.lat_long && val.lat_long != '') {
var name = val.name;
var id = val.id;
var depth = val.depth;
var children = val.children;
var pos = val.lat_long.split(',');
var lat = parseFloat(pos[0]);
var long = parseFloat(pos[1]);
var myLatLng = new google.maps.LatLng(lat, long);
var html = "<b>NAME=>" + name + "\nID=>" + id + "\nDEPTH=>" + depth+"</b>";
var marker = new google.maps.Marker({
position : myLatLng
});
mgr.addMarker(marker, depth);
markersArray.push(marker);
var boxText = document.createElement("div");
google.maps.event.addListener(marker, 'mouseover', function() {
/*
getStats(id);
// */
boxText.innerHTML = html;
var infoBoxOptions = {
content : boxText,
disableAutoPan : true,
maxWidth : 0,
pixelOffset : new google.maps.Size(-140, 0),
zIndex : null,
boxClass : "infoBox",
closeBoxMargin : "2px 2px 2px 2px",
closeBoxURL : "http://www.google.com/intl/en_us/mapfiles/close.gif",
infoBoxClearance : new google.maps.Size(10, 10),
isHidden : false,
pane : "floatPane",
enableEventPropagation : false,
};
ib.setOptions(infoBoxOptions);
ib.open(map, marker);
})
google.maps.event.addListener(marker, 'mouseout', function() {
ib.close();
})
google.maps.event.addListener(marker, 'click', function() {
map.panTo(this.getPosition());
// getLinks(id);
if (children > 0) {
loadMarkers({
pid : id
});
}
})
bounds.extend(myLatLng);
}
});
map.fitBounds(bounds);
});
});
}
// clear markers
function deleteOverlays(pid,callback){
if((markersArray)&&(markersArray.length > 1)) {
for (var x in markersArray) {
markersArray[x].setMap(null);
markersArray[x]=null;
}
markersArray=[];
};
callback(pid);
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
loadMarkers({
pid:5
});
So quickly, you can see that I send a parent id to the loadMarkers() among other things if necessary, and do some stuff, and then I call the deleteMarkers() function, the callback of which creates the markers, adds them to the manager and to the main markersArray[]
for brevity I'm not going to add the full Ajax call to xhr_get_descendants/ because without the Model it would be a bit meaningless.
Anyway, the function returns id, name, depth of each "child" of the parent id provided, as well as how many children each one of those children might have.
I mean... this should work!!! LOL
I've been looking at it wayyyy too long. I'd seriously appreciate any suggestions, or hints, or even a "why the hell are you doing it this way?"
The markers displayed by the MarkerMangager are not the markers you create (and supply as argument to mgr.addMarker() ), the MarkerManager creates new Instances and these Instances will not be deleted when you delete the Markers stored in markersArray(what doesn't have any visual effect, because the markers stored in markersArray are not visible)
You may call mgr.clearMarkers() in deleteOverlays() to delete also the Instances created by the MarkerManager, but the complete approach with the markersArray is unnecessary. You don't need this array at all, simply call mgr.clearMarkers() to remove the visible Markers.

google maps API3 drawing custom map icon based on user selection

Im working on a google maps plugin (there's always room for another right?) and I'm drawing a preview of the map my users will be inserting into their content. Im able to draw everything I set out to, custom content in the info window, setting the location (through places.Autocomplete) etc. The one thing that is escaping me is custom map icon isn't being drawn.
My goal is to have the default icon drawn on first load, and then update it when it changes
Im not getting any 404 or errors in the console, and I've checked my event handlers and they are all working. Can anyone tell me where I've going astray?
Here is what I have so far:
//Initilize the map
google.maps.event.addDomListener(window, 'load', initialize);
function initialize(infowindow) {
var init_center = new google.maps.LatLng(43.703793, -72.326187);
mapOptions = {
center: init_center,
zoom: parseFloat(mapZoomReturn),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel : false,
};
var input = document.getElementById('mapAddress');
var autocomplete = new google.maps.places.Autocomplete(input);
var infowindow = new google.maps.InfoWindow();
//var marker = new google.maps.Marker({
// position: init_center,
// map: map,
// icon: mapMarkerImageReturn
//});
// Draw the map
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
// marker needs to be set after the map
var marker = new google.maps.Marker({
position: init_center,
map: map,
icon: mapMarkerImageReturn
});
// Set up event listeners
// Info window DOM->MAP
google.maps.event.addDomListener(document.getElementById('mapInfoWindow'),
'change', function() {
mapInfoWindowReturn = escape(jQuery('#mapInfoWindow').val());
// get the extra content from feild, by this time the place_changed even will have fired at least once, so we have these values
infowindowPlace = get_info_bubble(locIcon, locName, locAddress, locPhone, locWeb, mapInfoWindowReturn); // returns formatted markup for info bubble
infowindow.setContent(infowindowPlace);
});
// Marker dropdown selection DOM->MAP
google.maps.event.addDomListener(document.getElementById('mapMarker'), 'change', update_maker);
// Custom marker text field DOM->MAP
google.maps.event.addDomListener(document.getElementById('mapMarkerImage'), 'change', update_maker );
function update_maker(){
//update the marker imge - (not working)
markerImage = get_marker_image(); // returns URL as string
marker.setIcon(markerImage);
marker.setPosition(locPlace.geometry.location);
marker.setMap(map);
}
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindowPlace = get_info_bubble(locIcon, locName, locAddress, locPhone, locWeb, mapInfoWindowReturn);
infowindow.close();
if (mapMarkerImageReturn !=='' || mapMarkerImageReturn !== false) marker.setVisible(false);
input.className = '';
locPlace = autocomplete.getPlace();
if (!locPlace.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (locPlace.geometry.viewport) {
map.fitBounds(locPlace.geometry.viewport);
mapCurrCenter = map.getCenter();
} else {
map.setCenter(locPlace.geometry.location);
map.setZoom(parseFloat(mapZoomReturn));
mapCurrCenter = map.getCenter();
}
// Set the marker image (not working)
markerImage = get_marker_image(); // returns URL as string
marker.setIcon(markerImage);
marker.setPosition(locPlace.geometry.location);
marker.setMap(map);
// get the location values for the info bubble
if (locPlace.address_components) {
//console.log(locPlace.address_components);
// Populate values for info bubble
locName = locPlace.name;
locIcon = locPlace.icon;
locAddress = locPlace.formatted_address;
locPhone = locPlace.formatted_phone_number;
locWeb = locPlace.website;
}
infowindowPlace = get_info_bubble(locIcon, locName, locAddress, locPhone, locWeb, mapInfoWindowReturn);
infowindow.setContent(infowindowPlace);
infowindow.open(map, marker);
});
}

Problem with my click event on GoogleMaps integration - Pulling data from a JSON file

I have GoogleMaps integrated into my site. I'm having a problem pulling my info from my JSON file into the Info Window when the markers are clicked.
Below is my current code:
/*********** Custom GoogleMaps functions ***********/
if (document.getElementById("events-map")) {
// set json path
var markerFile = '/scripts/json/find-events.json';
// set default map properties
var defaultLatlng = new google.maps.LatLng(41.4925, -99.9018);
// zoom level of the map
var defaultZoom = 4;
// variable for map
var map;
// variable for marker info window
var infowindow;
// List with all marker to check if exist
var markerList = {};
// option for google map object
var myOptions = {
zoom: defaultZoom,
center: defaultLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
/**
* Load Map
*/
function loadMap() {
// create new map make sure a DIV with id myMap exist on page
map = new google.maps.Map(document.getElementById("events-map"), myOptions);
// create new info window for marker detail pop-up
infowindow = new google.maps.InfoWindow();
// load markers
loadMarkers();
}
/**
* Load markers via ajax request from server
*/
function loadMarkers() {
// load marker jSon data
$.getJSON(markerFile, function(data) {
// loop all the markers
$.each(data, function(i, item) {
// add marker to map
loadMarker(item);
});
});
}
/**
* Load marker to map
*/
function loadMarker(makerData) {
// create new marker location
var myLatlng = new google.maps.LatLng(markerData['xCoordinate'], markerData['yCoordinate']);
// create new marker
var marker = new google.maps.Marker({
id: markerData['id'],
map: map,
title: markerData['propertyName'] ,
position: myLatlng
});
// add marker to list used later to get content and additional marker information
markerList[marker.id] = marker;
// add event listener when marker is clicked
// currently the marker data contain a dataurl field this can of course be done different
google.maps.event.addListener(marker, 'click', function() {
// show marker when clicked
showMarker(marker.id);
});
// add event when marker window is closed to reset map location
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(defaultLatlng);
map.setZoom(defaultZoom);
});
}
/**
* Show marker info window
*/
function showMarker(markerId) {
// get marker information from marker list
var marker = markerList[markerId];
// check if marker was found
if (marker) {
// get marker detail information from server
$.getJSON(markerFile, function(data) {
// show marker window
infowindow.setContent(data);
infowindow.open(map, marker);
});
} else {
alert('Error marker not found: ' + markerId);
}
}
google.maps.event.addDomListener(window, 'load', loadMap);
}
And here is the info that is contained in my JSON file:
{
"markers":[
{
"id":"1",
"xCoordinate" : 34.048928,
"yCoordinate" : -111.093731,
"propertyName" : "Arizona",
"propertyState" : "AZ",
"propertyPhone" : "777.777.7777",
"propertyEmail" : "test#example.com"
},
{
"id":"2",
"xCoordinate" : 38.582526,
"yCoordinate" : -92.510376,
"propertyName" : "Missouri",
"propertyState" : "MO",
"propertyPhone" : "777.777.7777",
"propertyEmail" : "test#example.com"
}
]
}
In
var marker = ...
$.getJSON(markerFile, function(data) {...marker...}
the function(data) is the callback that is called asynchronously when the result of the respective AJAX call is returned. At that moment the local variable marker is no longer in scope. You should apply a closure over the marker:
$.getJSON(markerFile, function(mapMarker) {
var m = mapMarker; // save the current marker in the closure
return function(data) { // return the required callback ...
// show marker window
infowindow.setContent(data);
infowindow.open(map, m);
} (marker) // ... applied to marker
});
There is a typo in your loadMarker function:
makerData should be markerData

Categories

Resources