How to remove individual markers in Google maps api3 - javascript

I know there are other solutions out there but none of them apply to my situation that easily because my markers are in a function and a marker is created from an external XML file where if you change the coordinates you add a marker in that current position. here is my code for the markers
var lastCoordinates={};
var polyline = new google.maps.Polyline({map:map})
var path = [];
function gotdata(){
if (xmlhttp.readyState == 4){
var d = xmlhttp.responseXML.documentElement
//innerHTML shouldn't work for XML-Nodes
y = d.getElementsByTagName("y")[0].textContent,
x = d.getElementsByTagName("x")[0].textContent,
h = [x,y].join('_');
if(lastCoordinates[h]){
return;
}
lastCoordinates[h]= new google.maps.Marker({
position: new google.maps.LatLng(x,y),
map: map,
title: 'YAY'
});
path.push(lastCoordinates[h].getPosition());
if (path.length >= 2) {
// display the polyline once it has more than one point
polyline.setMap(map);
polyline.setPath(path);
}
}
}

function gotdata() {
if (xmlhttp.readyState == 4){
count++;
// var d = xmlhttp.responseXML.documentElement
//innerHTML shouldn't work for XML-Nodes
y = count * 0.01; // d.getElementsByTagName("y")[0].textContent,
x = count * 0.01; //d.getElementsByTagName("x")[0].textContent,
h = [x, y].join('_');
if (lastCoordinates[h]) {
return;
}
lastCoordinates[h] = new google.maps.Marker({
position: new google.maps.LatLng(x, y),
map: map,
title: 'YAY'
});
rightclickableMarker(lastCoordinates[h],h);
map.panTo(lastCoordinates[h].getPosition());
path.push(lastCoordinates[h].getPosition());
if (path.length >= 2) {
// display the polyline once it has more than one point
polyline.setMap(map);
polyline.setPath(path);
}
}
}
function rightclickableMarker(marker, h) {
google.maps.event.addListener(marker, 'rightclick', function(evt) {
if(lastCoordinates[h] && lastCoordinates[h].setMap){
lastCoordinates[h].setMap(null);
delete marker;
}
});
}
proof of concept fiddle

Related

Get Variables from Qlik Sense to JavaScript

I'm new with JS and I have this extension from Qlik Sense that I'm trying to change, I need to point some pins according to a variable. If value of variable $type is 'A' I use some pin, if value is 'B' another and so on. But I really don't know how this extension get values from QS. Any help please?
Follow the JS:
require.config({
paths: {
async: '/extensions/GoogleMaps-Sense/lib/async',
markerclusterer: '/extensions/GoogleMaps-Sense/lib/markerclusterer'
},
shim: {
'markerclusterer': {
exports: 'MarkerClusterer'
}
}
});
define(['qlik', './src/properties', './src/styles', 'markerclusterer', './src/abbreviateNumber', 'qvangular', 'async!https://maps.googleapis.com/maps/api/js?key=AIzaSyASz5bdD789VzsLyki1JCKhSnCd5pEPY3Q'], function(qlik, properties, styles, MarkerClusterer, abbreviateNumber, qv) {
var BASE_URL = '/extensions/GoogleMaps-Sense/';
if (typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
if (typeof(Number.prototype.toDeg) === "undefined") {
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
}
}
return {
initialProperties: {
version: 1,
qHyperCubeDef: {
qSuppressZero: true,
qSuppressMissing: true
},
gmaps: {
cluster: {
oneStyle: false,
maxZoom: 10
},
map: {
mode: 'cluster',
customIcon: null,
iconUrl: '',
maxZoom: 18,
style: 'default'
}
}
},
definition: properties,
snapshot: {
canTakeSnapshot: true
},
paint: function($element, layout) {
$element.empty();
this.backendApi.cacheCube.enabled = false;
var _this = this;
var markers = [];
var selectedMarkers = [];
var rectangles = [];
var selectedRects = [];
var columns = layout.qHyperCube.qSize.qcx;
var totalheight = layout.qHyperCube.qSize.qcy;
var pageheight = Math.floor(10000 / columns);
var numberOfPages = Math.ceil(totalheight / pageheight);
var Promise = qv.getService('$q');
var promises = Array.apply(null, Array(numberOfPages)).map(function(data, index) {
var page = {
qTop: (pageheight * index) + index,
qLeft: 0,
qWidth: columns,
qHeight: pageheight
};
return this.backendApi.getData([page]);
}, this)
Promise.all(promises).then(function(data) {
render(data);
});
function render(data) {
var useCustomStyle = layout.gmaps.map.style !== 'default';
var hasMeasure = layout.qHyperCube.qMeasureInfo.length >= 1 ? true : false;
var hasPopup = layout.qHyperCube.qMeasureInfo.length === 2 ? true : false;
//The bounds object, used to determain which part of the map to show based on data
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
maxZoom: layout.gmaps.map.maxZoom,
panControl: true,
zoomControl: true,
overviewMapControl: false,
overviewMapControlOptions: {
opened: false
},
scaleControl: false,
streetViewControl: true,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.TERRAIN, google.maps.MapTypeId.HYBRID, 'map_style']
}
};
//Put the map on the page so give some visual feedback
var map = new google.maps.Map($element.get(0), mapOptions);
if (useCustomStyle) {
var selectedStyle = styles.filter(function(d) {
return d.key === layout.gmaps.map.style
});
var styledMap = new google.maps.StyledMapType(selectedStyle[0].data, {
name: layout.gmaps.map.style
});
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
};
//Create a marker for each row of data
data.forEach(function(obj) {
obj[0].qMatrix.forEach(function(row, index) {
if (row[0].qText == '-') return;
//Parse the dimension
var latlng = JSON.parse(row[0].qText);
//Reverse the order as QS sends long lat
var point = new google.maps.LatLng(latlng[1], latlng[0]);
//Create our marker - if we have a expression then use that otherwise default to just show locations
var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var marker = new google.maps.Marker({
position: point,
title: '',
icon: image,
customData: hasMeasure ? row[1].qText : 1,
qElem: row[0].qElemNumber
});
//If we have popup values for each marker create the popup windows
if (hasPopup) {
marker.infoWindow = new google.maps.InfoWindow({
content: row[2].qText
});
google.maps.event.addListener(marker, 'mouseover', function() {
this.infoWindow.open(map, this);
});
google.maps.event.addListener(marker, 'mouseout', function() {
this.infoWindow.close();
});
};
//Add click handler
google.maps.event.addListener(marker, 'click', (function(value) {
return function() {
_this.selectValues(0, [value], true);
highlightMarkers(value)
}
})(row[0].qElemNumber));
bounds.extend(point);
markers.push(marker);
});
});
//Fit map to bounds
map.fitBounds(bounds);
//Clustering enabled
if (layout.gmaps.map.mode === 'cluster') {
if (layout.gmaps.cluster.oneStyle) {
var clusterStyles = [{
opt_textColor: 'black',
url: BASE_URL + 'images/singlecluster.png',
height: 56,
width: 55
}];
};
var mcOptions = {
imagePath: BASE_URL + 'images/m',
styles: clusterStyles,
maxZoom: layout.gmaps.cluster.maxZoom
};
//Draw clusters onto map
var markerCluster = new MarkerClusterer(map, markers, mcOptions);
markerCluster.setCalculator(function(markers, clusterStyles) {
var index = 0,
count = markers.length,
total = count;
while (total !== 0) {
//Create a new total by dividing by a set number
total = parseInt(total / 5, 10);
//Increase the index and move up to the next style
index++;
}
index = Math.min(index, clusterStyles);
var measure = 0;
for (var i = 0, k = count; i < k; i++) {
measure += parseInt(markers[i].customData)
}
var abbreviatedValue = abbreviateNumber(measure)
return {
text: abbreviatedValue,
index: index
};
});
};
if (layout.gmaps.map.mode === 'marker') {
markers.forEach(function(d) {
d.setMap(map);
})
};
if (layout.gmaps.map.mode === 'boxes') {
markers.forEach(function(d) {
var distance = d.customData > 1 ? d.customData : 10;
var lat = d.position.lat();
var lng = d.position.lng();
var boxbounds = new google.maps.LatLngBounds(box(lat, lng, 225, distance), box(lat, lng, 45, distance))
var rect = new google.maps.Rectangle({
strokeColor: layout.gmaps.boxes.strokeFill,
strokeOpacity: +layout.gmaps.boxes.strokeOpacity,
strokeWeight: +layout.gmaps.boxes.strokeWeight,
fillColor: layout.gmaps.boxes.fillColor,
fillOpacity: +layout.gmaps.boxes.fillOpacity,
qElem: d.qElem,
map: map,
bounds: boxbounds
});
//Add click handler
google.maps.event.addListener(rect, 'click', (function(value) {
return function() {
_this.selectValues(0, [value], true);
highlightRects(value)
}
})(d.qElem));
rectangles.push(rect);
})
};
};
//In selection mode - loop over markers to highlight markers scheduled for selection.
function highlightMarkers(qElem) {
var idx = selectedMarkers.indexOf(qElem);
if (idx > -1) {
selectedMarkers.splice(idx, 1)
} else {
selectedMarkers.push(qElem)
}
markers.forEach(function(marker) {
if (selectedMarkers.indexOf(marker.qElem) === -1) {
marker.setOpacity(0.5)
} else {
marker.setOpacity(1);
}
});
};
//In selection mode - loop over markers to highlight markers scheduled for selection.
function highlightRects(qElem) {
var idx = selectedRects.indexOf(qElem);
if (idx > -1) {
selectedRects.splice(idx, 1)
} else {
selectedRects.push(qElem)
}
rectangles.forEach(function(marker) {
if (selectedRects.indexOf(marker.qElem) === -1) {
marker.setOptions({
fillOpacity: +layout.gmaps.boxes.fillOpacity / 2,
strokeOpacity: +layout.gmaps.boxes.strokeOpacity / 2
})
} else {
marker.setOptions({
fillOpacity: +layout.gmaps.boxes.fillOpacity,
strokeOpacity: +layout.gmaps.boxes.strokeOpacity
})
}
});
};
function box(lat, lng, brng, dist) {
this._radius = 6371;
var dist = dist / this._radius;
var brng = brng.toRad();
var lat1 = lat.toRad();
var lon1 = lng.toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) +
Math.cos(lat1) * Math.sin(dist) *
Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) *
Math.cos(lat1), Math.cos(dist) -
Math.sin(lat1) * Math.sin(lat2));
lon2 = (lon2 + 3 * Math.PI) % (2 * Math.PI) - Math.PI;
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
}
};
});
I think this might help
/**
* Retrieve the values of a list of variables.
*
* Since $q.all fails on the first error, we have to resolve all first
*
* #param {string[]} `varList` - The variable names.
* #param {object} `app` - The (Qlik Sense) app.
*
* #returns {Promise}
*
* #api public
*/
this.getEngineVarListValues = function ( app, varList ) {
if ( varList && Array.isArray( varList ) ) {
var promises = [];
varList.forEach( function ( variable ) {
promises.push( self.getEngineVarValue( app, variable ) )
} );
return $q.all( promises );
}
return $q.reject( new Error( 'getEngineVarListValues variable list passed.' ) );
};
Taken from https://github.com/stefanwalther/sense-extension-utils/blob/master/src/variable-utils.js
var app = qlik.currApp();
//get the variable content
app.variable.getContent('MYVAR',function ( reply ){
alert( JSON.stringify( reply ) );
});
source: http://help.qlik.com/en-US/sense-developer/June2017/Subsystems/APIs/Content/CapabilityAPIs/qlik-variable-interface.htm

Removing selected geojson feature with Google Maps JavaScript API

I'm using the Google Maps Javascript API to let users draw custom polygons with properties to be entered into a database. Before inserting them into the database though, they need to be able to delete selected shapes they've drawn.
This function isn't throwing any errors but it also isn't deleting the feature. What am I doing wrong?
var selectedshape;
function initMap() {
map = new google.maps.Map(document.getElementById('map2'), {
zoom: 1,
center: { lat: -1, lng: 1 }
});
function clearSelection() {
if (selectedShape) {
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
}
map.data.addListener('click', function(event) {
map.controls[google.maps.ControlPosition.TOP_RIGHT].clear()
setSelection(event.feature);
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(centerControlDiv);
map.data.revertStyle();
map.data.overrideStyle(event.feature, { strokeWeight: 8 });
selectID = event.feature.getProperty('uniqid')
selectID = event.feature.getProperty('uniqgeom')
$(".getSelectID").attr("id", selectID)
});
bounds = new google.maps.LatLngBounds();
map.data.addListener('addfeature', function(event) {
processPoints(event.feature.getGeometry(), bounds.extend, bounds);
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
var uniqid = "_" + Date.now();
feature_type = event.feature.getGeometry().getType()
if (feature_type == 'LineString') {
encoded_geom = event.feature.getProperty('uniqgeom') || google.maps.geometry.encoding.encodePath(event.feature.getGeometry().getArray());
} else {
encoded_geom = event.feature.getProperty('uniqgeom') || google.maps.geometry.encoding.encodePath(event.feature.getGeometry().getArray()[0].getArray())
}
event.feature.setProperty('encoded_geom', encoded_geom);
selectID = encoded_geom
$(".getSelectID").attr("id", selectID)
event.feature.setProperty('uniqid', uniqid);
});
function deleteSelectedShape() {
map.controls[google.maps.ControlPosition.TOP_RIGHT].clear()
if (selectedShape) {
map.data.forEach(function(feature) {
if (feature.getProperty('uniqid') == selectedShape.uniqid) {
map.data.remove(feature);
}
});
}
}
I believe the problem is a syntax error in
if (feature.getProperty('uniqid') == selectedShape.uniqid) {

Embedding a map inside a InfoWindow

I've attempted to embed a map inside an InfoWindow in order to create a pop up with a preview of the clustering. However once the InfoWindow is closed, the map div fails to render.
My attempt of a simplified jsfiddle, http://jsfiddle.net/behewur2/
function initialize() {
var mapOptions = {
center: {
lat: -34.9290,
lng: 138.6010
},
zoom: 8,
streetViewControl: false,
overviewMapControl: false
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var mcOptions = {
gridSize: 30,
zoomOnClick: false
};
var mcOptionsZoom = {
gridSize: 30,
zoomOnClick: true
};
var mc = new MarkerClusterer(map, [], mcOptions);
google.maps.event.addListener(mc, 'clusterclick',
function (cluster) {
if (typeof infowindow !== 'undefined') prevInfoWindow = infowindow;
infowindow = new google.maps.InfoWindow({
content: $('#inner-map-canvas')[0]
});
if (typeof prevInfoWindow !== 'undefined') prevInfoWindow.close();
infowindow.setPosition(cluster.getCenter());
infowindow.open(map);
google.maps.event.trigger(innermap, 'resize');
innermap.setZoom(innermap.getZoom());
for (var i = 0; i < cluster.getMarkers().length; i++) {
innermc.addMarker(
new google.maps.Marker({
position: cluster.getMarkers()[i].position,
map: innermap,
icon: cluster.getMarkers()[i].icon,
title: cluster.getMarkers()[i].title
}),
false);
}
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(mapOptions.center.lat, mapOptions.center.lng),
map: map,
icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=0|FF0000|000000'
});
mc.addMarker(marker, false);
var innermap = new google.maps.Map(document.getElementById("inner-map-canvas"), mapOptions);
var innermc = new MarkerClusterer(innermap, [], mcOptionsZoom);
}
google.maps.event.addDomListener(window, 'load', initialize);
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDKxl8sh1TEN61taio3wdbGwuSI8FVeQ5k"></script>
<script type="text/javascript" src="https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer_packed.js"></script>
<div id="map-canvas"></div>
<div id="inner-map-canvas">
</dev>
It would be better to dynamically create the div node in the infowindow, it is destroyed when the infowindow is closed.
google.maps.event.addListener(mc, 'clusterclick', function (cluster) {
if (typeof infowindow !== 'undefined') prevInfoWindow = infowindow;
var innermapNode = document.createElement("div");
innermapNode.setAttribute("id", "inner-map-canvas");
innermapNode.style.height = "300px";
innermapNode.style.width = "300px";
infowindow = new google.maps.InfoWindow({
content: innermapNode
});
if (typeof prevInfoWindow !== 'undefined') prevInfoWindow.close();
infowindow.setPosition(cluster.getCenter());
infowindow.open(map);
innermap = new google.maps.Map(innermapNode, mapOptions);
innermc = new MarkerClusterer(innermap, [], mcOptionsZoom);
google.maps.event.addListener(infowindow, 'domready', function () {
google.maps.event.trigger(innermap, 'resize');
// innermap.setZoom(innermap.getZoom());
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < cluster.getMarkers().length; i++) {
innermc.addMarker(
new google.maps.Marker({
position: cluster.getMarkers()[i].position,
map: innermap,
icon: cluster.getMarkers()[i].icon,
title: cluster.getMarkers()[i].title,
keycount: cluster.getMarkers()[i].keycount
}),
false);
bounds.extend(cluster.getMarkers()[i].position);
}
google.maps.event.trigger(innermap, 'resize');
innermap.fitBounds(bounds);
});
});
proof of concept fiddle
code snippet:
function colorForCount(count) {
if (count == 1) return '4080FE';
if (count == 2) return 'F7C207';
if (count > 2 && count < 5) return 'F50D07';
if (count >= 5) return 'FF00F0';
else return 'B600FF';
}
var innermap;
var innermc;
function initialize() {
var mapOptions = {
center: {
lat: -34.9290,
lng: 138.6010
},
zoom: 8,
streetViewControl: false,
overviewMapControl: false
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var mcStyles = [{
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m1.png",
height: 53,
width: 53
}, {
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m2.png",
height: 53,
width: 53
}, {
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m3.png",
height: 53,
width: 53
}, {
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m4.png",
height: 53,
width: 53
}, {
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m5.png",
height: 53,
width: 53
}];
var mcOptions = {
gridSize: 30,
zoomOnClick: false,
styles: mcStyles
};
var mcOptionsZoom = {
gridSize: 30,
zoomOnClick: true,
styles: mcStyles
};
var mc = new MarkerClusterer(map, [], mcOptions);
mc.setCalculator(function(markers, numStyles) {
var count = markers.length;
var total = 0;
var max = 0;
var index = 0;
if (max == 1) index = 0;
if (max == 2) index = 2;
if (max > 2 && max < 5) index = 3;
if (max >= 5) index = 4;
return {
text: count,
index: index
};
});
google.maps.event.addListener(mc, 'clusterclick',
function(cluster) {
if (typeof infowindow !== 'undefined') prevInfoWindow = infowindow;
var innermapNode = document.createElement("div");
innermapNode.setAttribute("id", "inner-map-canvas");
innermapNode.style.height = "300px";
innermapNode.style.width = "300px";
infowindow = new google.maps.InfoWindow({
content: innermapNode
});
if (typeof prevInfoWindow !== 'undefined') prevInfoWindow.close();
infowindow.setPosition(cluster.getCenter());
infowindow.open(map);
innermap = new google.maps.Map(innermapNode, mapOptions);
innermc = new MarkerClusterer(innermap, [], mcOptionsZoom);
google.maps.event.addListener(infowindow, 'domready', function() {
google.maps.event.trigger(innermap, 'resize');
// innermap.setZoom(innermap.getZoom());
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < cluster.getMarkers().length; i++) {
innermc.addMarker(
new google.maps.Marker({
position: cluster.getMarkers()[i].position,
map: innermap,
icon: cluster.getMarkers()[i].icon,
title: cluster.getMarkers()[i].title,
keycount: cluster.getMarkers()[i].keycount
}),
false);
bounds.extend(cluster.getMarkers()[i].position);
}
google.maps.event.trigger(innermap, 'resize');
innermap.fitBounds(bounds);
});
});
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
var mapBnds = map.getBounds();
var mapSpan = mapBnds.toSpan();
for (var i = 0; i < 25; i++) {
var latRan = (Math.random() * mapSpan.lat() / 2) + mapSpan.lat() / 4;
var lngRan = (Math.random() * mapSpan.lng() / 2) + mapSpan.lng() / 4;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(mapBnds.getSouthWest().lat() + latRan, mapBnds.getSouthWest().lng() + lngRan),
map: map,
icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + i + '|FF0000|000000'
});
mc.addMarker(marker, false);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
/**
* Pull out the unique keys and counts.
* #param {Object} json The Inventory object.
* #return {Array.<{portal:{portalGuid:string,portalLocation:string,
* portalImageUrl:string,portalTitle:string,portalAddress:string},
* count:number}>}
*/
function getKeys(json) {
// parse the json string
var inventory = json.gameBasket.inventory;
// loop over the inventory items to find keys
var keys = [];
var iitckeys = {};
for (var i = 0; i < inventory.length; i++) {
// if it's a key, attempt to add to the key list
var item = inventory[i];
if (item[2].resource && item[2].resource.resourceType == "PORTAL_LINK_KEY") {
addKey(keys, iitckeys, item[2].portalCoupler);
} else if (item[2].resource && (item[2].resource.resourceType == "CAPSULE" || item[2].resource.resourceType == "INTEREST_CAPSULE")) {
parseCapsule(keys, iitckeys, item[2].container.stackableItems);
}
}
// return back the keys
return {
keys: keys,
iitckeys: iitckeys
};
}
/**
* Parse the items within a capsule.
* #param {Array.<{portal:{portalGuid:string,portalLocation:string,
* portalImageUrl:string,portalTitle:string,portalAddress:string},
* count:number}>} keys The current key array.
* #param {Array.<Object>} items The capsule's contents.
*/
function parseCapsule(keys, iitckeys, items) {
for (var i = 0; i < items.length; i++) {
if (typeof items[i].exampleGameEntity[2].resource !== 'undefined') {
if (items[i].exampleGameEntity[2].resource.resourceType == "PORTAL_LINK_KEY") {
var count = items[i].itemGuids.length;
while (count > 0) {
addKey(keys, iitckeys, items[i].exampleGameEntity[2].portalCoupler);
count--;
}
}
}
}
}
/**
* Add a key def to the keys list.
* #param {Array.<{portal:{portalGuid:string,portalLocation:string,
* portalImageUrl:string,portalTitle:string,portalAddress:string},
* count:number}>} keys The current key array.
* #param {{portalGuid:string,portalLocation:string,portalImageUrl:string,
* portalTitle:string,portalAddress:string}} keyDef The key definition.
*/
function addKey(keys, iitckeys, keyDef) {
// try to find the key and increment the count
console.log("keyDef : " + keyDef);
for (var i = 0; i < keys.length; i++) {
if (keys[i].portal.portalGuid == keyDef.portalGuid) {
keys[i].count++;
iitckeys[keyDef.portalGuid] ++;
return;
}
}
// couldn't find the key, add it
keys.push({
portal: keyDef,
count: 1
});
iitckeys[keyDef.portalGuid] = 1;
}
function getLatLng(location) {
var newLoc = parseInt(location, 16);
//if MSB is set
if ((newLoc & 0x80000000) !== 0x00000000) {
console.log("neg");
return (newLoc - 0x100000000) / 1E6;
} else {
console.log("pos");
return newLoc / 1E6;
}
}
body,
html {
height: 100%;
width: 100%;
}
#map-canvas {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.cluster img {
width: 53px;
height: 53px;
}
#commands {
width: 100%;
}
#inner-map-canvas {
width: 300px;
height: 300px;
}
<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>
<script src="https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script>
<div id="map-canvas"></div>
<div id="keyjson"></div>

Google maps api v3 - Map Toolbar implementation - settimeout for dblclick zoom

I use Map Toolbar implementation for javascript Google maps api v3:
http://nettique.free.fr/gmap/toolbar.html
It's working great! My only matter is that I wanna keep the dblclick event to zoom while creating a polygon, but now, if I double-click, I create a new marker and delete it right away.
With an older version of my code, I was using a timeout like explained here:
https://stackoverflow.com/a/8417447/1895428
but now, no matter where I put the setTimeout function, it makes no change. Does anybody knows where to put it?
I tried to modify the addPoint function in the js code (http://nettique.free.fr/gmap/lib/mapToolbar.js), but it didn't work:
addPoint : function(e, poly, index) { //alert(MapToolbar["shapeCounter"]);
update_timeout = setTimeout(function(){
var e = (typeof e.latLng != "undefined")? e.latLng : e,
image = new google.maps.MarkerImage('/image/marker-edition.png',
new google.maps.Size(9, 9),
new google.maps.Point(0, 0),
new google.maps.Point(5, 5)),
imageover = new google.maps.MarkerImage('/image/marker-edition-over.png',
new google.maps.Size(9, 9),
new google.maps.Point(0, 0),
new google.maps.Point(5, 5)),
path = poly.getPath(),
index = (typeof index != "undefined")? index : path.length,
markers = (poly.markers)? poly.markers : new google.maps.MVCArray,
marker = new google.maps.Marker({
position: e,
map: map[mapkey],
draggable: true,
icon: image
});
marker.index = index;
path.insertAt(index, e);
markers.insertAt(index, marker)
if(arguments[2]){
MapToolbar.reindex(markers);
} }, 200);
//click on a polymarker will delete it
google.maps.event.addListener(marker, 'click', function() {
marker.setMap(null);
markers.removeAt(marker.index);
path.removeAt(marker.index);
MapToolbar.reindex(markers);
if(markers.getLength() == 0){
MapToolbar.removeFeature(poly.id);
}
});
/*
google.maps.event.addListener(marker, 'dragstart', function() {
MapToolbar.currentlyDragging = true;
})
*/
google.maps.event.addListener(marker, 'position_changed', function() {
path.setAt(marker.index, marker.getPosition());
})
google.maps.event.addListener(marker, 'dragend', function() {
//MapToolbar.currentlyDragging = false;
path.setAt(marker.index, marker.getPosition());
var position = marker.getPosition(),
p;
//get previous point
if(typeof path.getAt(marker.index-1) != "undefined"){
var m1 = path.getAt(marker.index -1);
p = MapToolbar.getMidPoint(position, m1);
MapToolbar.addPoint(p, poly, marker.index);
}
// get next point
if(typeof path.getAt(marker.index+1) != "undefined"){
var m2 = path.getAt(marker.index+1);
p = MapToolbar.getMidPoint(position, m2);
MapToolbar.addPoint(p, poly, marker.index+1);
}
});
google.maps.event.addListener(marker, 'mouseover', function() {
this.setIcon(imageover);
});
google.maps.event.addListener(marker, 'mouseout', function() {
this.setIcon(image);
});
MapToolbar["isStarted"]++;
}
Not sure if this will work but following the stackoverflow example you have to change only listener code:
addPoint : function(e, poly, index) {
var e = (typeof e.latLng != "undefined")? e.latLng : e,
...
//click on a polymarker will delete it
var update_timeout = null;
google.maps.event.addListener(marker, 'click', function() {
update_timeout = setTimeout(function() {
marker.setMap(null);
markers.removeAt(marker.index);
path.removeAt(marker.index);
MapToolbar.reindex(markers);
if(markers.getLength() == 0){
MapToolbar.removeFeature(poly.id);
}
}, 200);
});
google.maps.event.addListener(marker, 'dblclick', function(event) {
clearTimeout(update_timeout);
});
...

Clear circles in google maps

I'm trying to remove some circles from a map but isn't working as expected. Here are my code.
Function I have used to draw circles:
for (var city in citymap) {
var circleOptions = {
map: GoogleMap,
radius: distance, //In meters
strokeColor: circleColor,
fillOpacity: 0.0,
strokeWeight: circleWeight,
strokeOpacity: 0.5,
center: citymap[city].center,
};
// Add the circle for this city to the map.
cityCircle[circleId] = new google.maps.Circle(circleOptions);
}
Looking at the cityCircle Array I have eight elements, from 0 to 7. I tryed to remove them using the following function grabbed here stackoverflow forum:
function RemoveOverlays(overlays) {
for (var i = 0; i < overlays.length; i++) {
overlays[i].setMap(null);
}
I call the function inside of an else if loop like this:
else if (zoom <6 ){
if (typeof cityCircle[0] !=undefined && cityCircle[0] !=null) {
RemoveOverlays(cityCircle)
}
}
At the end I have just the latest drawn circle removed. What I'm doing wrong? Thanks!
Here is the entire code.
// Listeners for newly created Map
google.maps.event.addListener(GoogleMap, 'center_changed', function() {
localStorage['CenterLat'] = GoogleMap.getCenter().lat();
localStorage['CenterLon'] = GoogleMap.getCenter().lng();
});
google.maps.event.addListener(GoogleMap, 'zoom_changed', function() {
localStorage['ZoomLvl'] = GoogleMap.getZoom();
var zoom = GoogleMap.getZoom(); //gets zoom level.
if (SiteCircles && zoom >=6) {
for (var i=0;i<SiteCirclesDistances.length;i++) {
for (var circleId=0; circleId < size; circleId++) {
drawCircle(marker, SiteCirclesDistances[i], circleId); // in meters
}
}
} else if (zoom <6 ){
if (typeof cityCircle[index] !="undefined" && cityCircle.length >0) {
RemoveOverlays(cityCircle)
}
}
});
// Add home marker if requested
if (SiteShow && (typeof SiteLat !== 'undefined' || typeof SiteLon !== 'undefined')) {
for (var city in citymap) {
var siteMarker = new google.maps.LatLng(citymap[city].SiteLat, citymap[city].SiteLon);
var markerImage = circleImage; //Defined on config.js
var marker = new google.maps.Marker({
position: siteMarker,
map: GoogleMap,
icon: {url:markerImage, scaledSize: new google.maps.Size(32, 32)},
title: citymap[city].title,
zIndex: -99999
});
}
function drawCircle(marker, distance, circleId) {
if (typeof distance === 'undefined') {
return false;
if (!(!isNaN(parseFloat(distance)) && isFinite(distance)) || distance < 0) {
return false;
}
}
distance *= 1000.0;
if (!Metric) {
distance *= 1.852;
}
//Create range circles
for (var city in citymap) {
var circleOptions = {
map: GoogleMap,
radius: distance, //In meters
strokeColor: circleColor,
fillOpacity: 0.0,
strokeWeight: circleWeight,
strokeOpacity: 0.5,
center: citymap[city].center,
};
// Add the circle for this city to the map.
cityCircle[circleId] = new google.maps.Circle(circleOptions);
}
}
typeof operator convert type to String value so you should check by:
typeof cityCircle[0] != "undefined"

Categories

Resources