Related
I need to be able to highlight features in a bounding box using Mapbox GL as shown in this example. My map also needs to have the ability to change the style layer, e.g. changing the base style from mapbox://styles/mapbox/light-v10 to mapbox://styles/mapbox/satellite-v9. This has been challenging because Mapbox GL does not natively support the concept of "basemaps" like, e.g. leaflet does.
My solution, after much searching (I believe I eventually followed a workaround posted in a github issue) involved:
Using map.on('style.load') instead of map.on('load') as shown in the example (I believe map.on('style.load') is not part of their public API, but I could be wrong) and,
Iterating through an array of sources/layers (see the vectorTileLayers variable in the code below) to add vector tiles layers to the map every time a new style is loaded.
This works brilliantly for me in some ways - I'm able to add an arbitrary number of vector tile sources to the array, and they are all added back to the map if the base style is changed. However, I am unable to add a query feature following the example provided by Mapbox if the sources/layers are added to the map in an array and iterated through as shown below. The bounding feature works, but when it is drawn, and released, I see the error show by running the snippet below.
This is a simplified version my actual problem that will allow others to run and manipulate the code. In reality, I'm adding my own vector tile layers (stored in the vectorTileLayers array, which works without issue. When I try and add another layer with the same source and different styling, as shown in the example, I'm unable to actually query the desired layer. Any help would be greatly appreciated. Just FYI - the toggleable layers buttons are not showing up in this snippet, but it's not critical to solve the problem.
mapboxgl.accessToken = 'pk.eyJ1IjoiamFtZXljc21pdGgiLCJhIjoiY2p4NTRzdTczMDA1dzRhbXBzdmFpZXV6eCJ9.-k7Um-xmYy4xhNDN6kDvpg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-98, 38.88],
minZoom: 2,
zoom: 3
});
var vectorTileLayers = [{
source: {
type: 'vector',
url: 'mapbox://mapbox.82pkq93d'
},
layer: {
id: 'counties',
type: 'fill',
source: 'counties',
'source-layer': 'original',
paint: {
'fill-outline-color': 'rgba(0,0,0,0.1)',
'fill-color': 'rgba(0,0,0,0.1)'
},
}
},
{
source: {
type: 'vector',
url: 'mapbox://mapbox.82pkq93d'
},
layer: {
id: 'counties-highlighted',
type: 'fill',
source: 'counties',
'source-layer': 'original',
paint: {
'fill-outline-color': '#484896',
'fill-color': '#6e599f',
'fill-opacity': 0.75
},
filter: ['in', 'FIPS', '']
}
}
]
map.on('style.load', function() {
for (var i = 0; i < vectorTileLayers.length; i++) {
var tileLayer = vectorTileLayers[i];
map.addSource(tileLayer.layer.source, tileLayer.source);
map.addLayer(tileLayer.layer);
}
var layerList = document.getElementById('basemapmenu');
var inputs = layerList.getElementsByTagName('input');
function switchLayer(layer) {
var layerId = layer.target.id;
map.setStyle('mapbox://styles/mapbox/' + layerId);
}
for (var i = 0; i < inputs.length; i++) {
inputs[i].onclick = switchLayer;
}
});
// Disable default box zooming.
map.boxZoom.disable();
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false
});
var canvas = map.getCanvasContainer();
var start;
var current;
var box;
canvas.addEventListener('mousedown', mouseDown, true);
// Return the xy coordinates of the mouse position
function mousePos(e) {
var rect = canvas.getBoundingClientRect();
return new mapboxgl.Point(
e.clientX - rect.left - canvas.clientLeft,
e.clientY - rect.top - canvas.clientTop
);
}
function mouseDown(e) {
// Continue the rest of the function if the shiftkey is pressed.
if (!(e.shiftKey && e.button === 0)) return;
// Disable default drag zooming when the shift key is held down.
map.dragPan.disable();
// Call functions for the following events
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
document.addEventListener('keydown', onKeyDown);
// Capture the first xy coordinates
start = mousePos(e);
}
function onMouseMove(e) {
// Capture the ongoing xy coordinates
current = mousePos(e);
// Append the box element if it doesnt exist
if (!box) {
box = document.createElement('div');
box.classList.add('boxdraw');
canvas.appendChild(box);
}
var minX = Math.min(start.x, current.x),
maxX = Math.max(start.x, current.x),
minY = Math.min(start.y, current.y),
maxY = Math.max(start.y, current.y);
// Adjust width and xy position of the box element ongoing
var pos = 'translate(' + minX + 'px,' + minY + 'px)';
box.style.transform = pos;
box.style.WebkitTransform = pos;
box.style.width = maxX - minX + 'px';
box.style.height = maxY - minY + 'px';
}
function onMouseUp(e) {
// Capture xy coordinates
finish([start, mousePos(e)]);
}
function onKeyDown(e) {
// If the ESC key is pressed
if (e.keyCode === 27) finish();
}
function finish(bbox) {
// Remove these events now that finish has been called.
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('keydown', onKeyDown);
document.removeEventListener('mouseup', onMouseUp);
if (box) {
box.parentNode.removeChild(box);
box = null;
}
// If bbox exists. use this value as the argument for `queryRenderedFeatures`
if (bbox) {
var features = map.queryRenderedFeatures(bbox, {
layers: ['counties']
});
if (features.length >= 1000) {
return window.alert('Select a smaller number of features');
}
// Run through the selected features and set a filter
// to match features with unique FIPS codes to activate
// the `counties-highlighted` layer.
var filter = features.reduce(
function(memo, feature) {
memo.push(feature.properties.FIPS);
return memo;
},
['in', 'FIPS']
);
map.setFilter('counties-highlighted', filter);
}
map.dragPan.enable();
}
map.on('mousemove', function(e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['counties-highlighted']
});
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = features.length ? 'pointer' : '';
if (!features.length) {
popup.remove();
return;
}
var feature = features[0];
popup
.setLngLat(e.lngLat)
.setText(feature.properties.COUNTY)
.addTo(map);
});
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
#basemapmenu {
position: absolute;
display: inline-block;
background-color: transparent;
bottom: 0;
left: 0;
margin-left: 10px;
margin-bottom: 40px;
}
.boxdraw {
background: rgba(56, 135, 190, 0.1);
border: 2px solid #3887be;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
}
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet"/>
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
<div id="map"></div>
<div id='basemapmenu'>
<input id='light-v10' class='btn btn-outline-primary' type='button' name='rtoggle' value='Light' checked='checked'>
<input id='dark-v10' class='btn btn-outline-primary' type='button' name='rtoggle' value='Dark'>
<input id='satellite-v9' class='btn btn-outline-primary' type='button' name='rtoggle' value='Satellite'>
</div>
I ran you code locally and found the problem!
You are trying to add same source twice and mapbox was giving you error for that, if you check your Console:
Problem: There can be only one source with one ID on Map
Error: There is already a source with this ID
After first loop execute successfully. On second iteration, it fails to add same source twice, code breaks here and doesn't continue further. Hence doesn't add second layer(therefore no functionality works thereafter!)
Fix:(Added a small check to not add same source if already added)
map.on('style.load', function () {
for (var i = 0; i < vectorTileLayers.length; i++) {
var tileLayer = vectorTileLayers[i];
if (!map.getSource(tileLayer.layer.source,)) //FIX
map.addSource(tileLayer.layer.source, tileLayer.source);
map.addLayer(tileLayer.layer);
}
var layerList = document.getElementById('basemapmenu');
var inputs = layerList.getElementsByTagName('input');
function switchLayer(layer) {
var layerId = layer.target.id;
map.setStyle('mapbox://styles/mapbox/' + layerId);
}
for (var i = 0; i < inputs.length; i++) {
inputs[i].onclick = switchLayer;
}
});
I can see the Code is working fine:
Hope this will fix the problem.
I'll leave the above answer from Dolly as accepted because it answers my original question exactly. Unforunately, it didn't exactly solve my actual problem. After some additional fiddling, I wanted to post a fully functional version for reference in case people come across this looking for a solution to adding toggleable "basemap" layers in Mapbox GL with or without user interactivity options like this one.
The solution above does not work after toggling between basemap layers. The vector tile layers are not reloaded properly. The solution below seems to do the trick. It uses map.on('styledata' ...) rather than map.on('style.load' ...), which seems to allow for loading layers by the more conventional method of first calling map.addSource() followed by map.addLayer(). You can load a single source, and then an arbitrary number of layers pointing to that source. So in my "real world" example, I load 3 sources, and 5 layers from those sources.
(FYI - for some reason the built-in snippet tool from stack overflow isn't rendering the basemap buttons. If you copy the code exactly into JS fiddle or codepen it will work)
I hope this helps future humans - it seems like lots of people have had problems with managing Mapbox styles with custom layers on top. I certainly have.
mapboxgl.accessToken =
"pk.eyJ1IjoiamFtZXljc21pdGgiLCJhIjoiY2p4NTRzdTczMDA1dzRhbXBzdmFpZXV6eCJ9.-k7Um-xmYy4xhNDN6kDvpg";
var map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/light-v10",
center: [-98, 38.88],
minZoom: 2,
zoom: 3
});
map.on("styledata", function() {
map.addSource("counties", {
type: "vector",
url: "mapbox://mapbox.82pkq93d"
});
map.addLayer({
id: "counties",
type: "fill",
source: "counties",
"source-layer": "original",
paint: {
"fill-outline-color": "rgba(0,0,0,0.1)",
"fill-color": "rgba(0,0,0,0.1)"
}
});
map.addLayer({
id: "counties-highlighted",
type: "fill",
source: "counties",
"source-layer": "original",
paint: {
"fill-outline-color": "#484896",
"fill-color": "#6e599f",
"fill-opacity": 0.75
},
filter: ["in", "FIPS", ""]
});
var layerList = document.getElementById("basemapmenu");
var inputs = layerList.getElementsByTagName("input");
function switchLayer(layer) {
var layerId = layer.target.id;
map.setStyle("mapbox://styles/mapbox/" + layerId);
}
for (var i = 0; i < inputs.length; i++) {
inputs[i].onclick = switchLayer;
}
});
// Disable default box zooming.
map.boxZoom.disable();
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false
});
var canvas = map.getCanvasContainer();
var start;
var current;
var box;
canvas.addEventListener("mousedown", mouseDown, true);
// Return the xy coordinates of the mouse position
function mousePos(e) {
var rect = canvas.getBoundingClientRect();
return new mapboxgl.Point(
e.clientX - rect.left - canvas.clientLeft,
e.clientY - rect.top - canvas.clientTop
);
}
function mouseDown(e) {
// Continue the rest of the function if the shiftkey is pressed.
if (!(e.shiftKey && e.button === 0)) return;
// Disable default drag zooming when the shift key is held down.
map.dragPan.disable();
// Call functions for the following events
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
document.addEventListener("keydown", onKeyDown);
// Capture the first xy coordinates
start = mousePos(e);
}
function onMouseMove(e) {
// Capture the ongoing xy coordinates
current = mousePos(e);
// Append the box element if it doesnt exist
if (!box) {
box = document.createElement("div");
box.classList.add("boxdraw");
canvas.appendChild(box);
}
var minX = Math.min(start.x, current.x),
maxX = Math.max(start.x, current.x),
minY = Math.min(start.y, current.y),
maxY = Math.max(start.y, current.y);
// Adjust width and xy position of the box element ongoing
var pos = "translate(" + minX + "px," + minY + "px)";
box.style.transform = pos;
box.style.WebkitTransform = pos;
box.style.width = maxX - minX + "px";
box.style.height = maxY - minY + "px";
}
function onMouseUp(e) {
// Capture xy coordinates
finish([start, mousePos(e)]);
}
function onKeyDown(e) {
// If the ESC key is pressed
if (e.keyCode === 27) finish();
}
function finish(bbox) {
// Remove these events now that finish has been called.
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("keydown", onKeyDown);
document.removeEventListener("mouseup", onMouseUp);
if (box) {
box.parentNode.removeChild(box);
box = null;
}
// If bbox exists. use this value as the argument for `queryRenderedFeatures`
if (bbox) {
var features = map.queryRenderedFeatures(bbox, {
layers: ["counties"]
});
if (features.length >= 1000) {
return window.alert("Select a smaller number of features");
}
// Run through the selected features and set a filter
// to match features with unique FIPS codes to activate
// the `counties-highlighted` layer.
var filter = features.reduce(
function(memo, feature) {
memo.push(feature.properties.FIPS);
return memo;
}, ["in", "FIPS"]
);
map.setFilter("counties-highlighted", filter);
}
map.dragPan.enable();
}
map.on("mousemove", function(e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ["counties-highlighted"]
});
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = features.length ? "pointer" : "";
if (!features.length) {
popup.remove();
return;
}
var feature = features[0];
popup.setLngLat(e.lngLat).setText(feature.properties.COUNTY).addTo(map);
});
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
#basemapmenu {
position: absolute;
display: inline-block;
background-color: transparent;
bottom: 0;
left: 0;
margin-left: 10px;
margin-bottom: 40px;
}
.boxdraw {
background: rgba(56, 135, 190, 0.1);
border: 2px solid #3887be;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
}
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
<div id="map"></div>
<div id='basemapmenu'>
<input id='light-v10' class='btn btn-outline-primary' type='button' name='rtoggle' value='Light' checked='checked'>
<input id='dark-v10' class='btn btn-outline-primary' type='button' name='rtoggle' value='Dark'>
<input id='satellite-v9' class='btn btn-outline-primary' type='button' name='rtoggle' value='Satellite'>
</div>
I have this almost working; but instead of it following the kendo modal when dragged, it's following the mouse pointer at all times...
So, currently it's following the mouse pointer and so is the modal; but this is horrible for usability so would just like to stay with and follow the modal on the standard click and drag.
attempt A.) Below is the JavaScript, here is the live demo CodePen. The line should always be with the modal for point B, which it's doing; but the modal should only be movable on drag.
require([
"esri/Map",
"esri/views/MapView",
"esri/Graphic",
"esri/layers/GraphicsLayer",
"esri/geometry/support/webMercatorUtils",
"dojo/dom",
],
function init (Map, MapView, Graphic, GraphicsLayer, webMercatorUtils, dom) {
var map = new Map({
basemap: "topo-vector"
});
var view = new MapView({
container: "viewDiv",
map: map,
center: [-80.96135253906438, 35.9411934679851],
zoom: 3
});
var graphicsLayer = new GraphicsLayer();
map.add(graphicsLayer);
var simpleLineSymbol = {
type: "simple-line",
color: [13,121,190, .9],
style: "short-dash",
width: 3
};
var coordinatesAx;
var coordinatesAy;
var coordinatesBx ;
var coordinatesBy;
var moveAlong = false;
var windowElem;
view.when(function(){
view.on("pointer-move", showCoordinates);
});
// NEW: Stop/start moving the modal along with the pointer by map click
view.when(function(){
view.on("click", function () { moveAlong = !moveAlong;});
});
coordinatesAx = -80.96135253906438;
coordinatesAy = 35.9411934679851;
document.getElementById("modal").onclick = function fun() {
windowElem = document.querySelector('.k-window');
moveAlong = true;
// Bind Kendo dialog dragstart to movement
$("#dialog").data('kendoWindow').bind("dragstart", function (ev) {
//graphicsLayer.removeAll();
moveAlong = true;
showCoordinates(ev);
})
}
function showCoordinates(evt) {
var point = view.toMap({x: evt.x, y: evt.y});
var mp = webMercatorUtils.webMercatorToGeographic(point);
dom.byId("info").innerHTML = mp.x.toFixed(3) + ", " + mp.y.toFixed(3);
coordinatesBx = mp.x.toFixed(3);
coordinatesBy = mp.y.toFixed(3);
var polyline = {
type: "polyline",
paths: [
[coordinatesAx, coordinatesAy],
[coordinatesBx, coordinatesBy]
]
};
var polylineGraphic = new Graphic({
geometry: polyline,
symbol: simpleLineSymbol
})
if (moveAlong) {
if (graphicsLayer.graphics.items.length < 0) {
graphicsLayer.add(polylineGraphic)
} else {
// Recreate the line and reposition the modal
graphicsLayer.removeAll();
graphicsLayer.add(polylineGraphic)
windowElem.style.top = evt.y + 0 + "px";
windowElem.style.left = evt.x + 0 + "px";
}
}
}
});
Attempt B.) Update: I have tried going with this logic I found; although I believe it's arcgis 3.3.. and still can't get it to integrate into my CodePen prototype. Anyways I think this is the logic; just can't seem to get it right.
$profileWindow = $("#" + elem).parents(".outter-div-wrapper");
profileWindowOffset = $profileWindow.offset();
profileWindowWidth = $profileWindow.outerWidth();
profileWindowHeight = $profileWindow.outerHeight();
screenPointTopLeft = new Point(profileWindowOffset.left, profileWindowOffset.top, app.ui.mapview.map.spatialReference);
screenPointTopRight = new Point(profileWindowOffset.left + profileWindowWidth, profileWindowOffset.top, app.ui.mapview.map.spatialReference);
screenPointBottomLeft = new Point(profileWindowOffset.left, profileWindowOffset.top + profileWindowHeight, app.ui.mapview.map.spatialReference);
screenPointBottomRight = new Point(profileWindowOffset.left + profileWindowWidth, profileWindowOffset.top + profileWindowHeight, app.ui.mapview.map.spatialReference);
arrayOfCorners.push(screenPointTopLeft);
arrayOfCorners.push(screenPointTopRight);
arrayOfCorners.push(screenPointBottomLeft);
arrayOfCorners.push(screenPointBottomRight);
//convert to screenpoint
graphicsScreenPoint = esri.geometry.toScreenPoint(app.ui.mapview.map.extent, app.ui.mapview.map.width, app.ui.mapview.map.height, self.mapPoint_);
//find closest Point
profileWindowScreenPoint = this.findClosest(arrayOfCorners, graphicsScreenPoint);
//convert from screen point to map point
profileWindowClosestMapPoint = app.ui.mapview.map.toMap(profileWindowScreenPoint);
mapProfileWindowPoint.push(profileWindowClosestMapPoint.x);
mapProfileWindowPoint.push(profileWindowClosestMapPoint.y);
And here is the CodePen with the above attempt added.
Try replacing the JS in your codepen with this code. Needs a bit of work but I think it basically does what you want.
What I changed was to hook into dragstart and dragend of the modal, and use a mouse motion event handler on the document when dragging the modal. I used the document because the events wouldn't get through the dialog to the view behind it.
require([
"esri/Map",
"esri/views/MapView",
"esri/Graphic",
"esri/layers/GraphicsLayer",
"esri/geometry/support/webMercatorUtils",
"dojo/dom",
],
function init(Map, MapView, Graphic, GraphicsLayer, webMercatorUtils, dom) {
var map = new Map({
basemap: "topo-vector"
});
var view = new MapView({
container: "viewDiv",
map: map,
center: [-80.96135253906438, 35.9411934679851],
zoom: 3
});
var graphicsLayer = new GraphicsLayer();
map.add(graphicsLayer);
var simpleLineSymbol = {
type: "simple-line",
color: [13, 121, 190, .9],
style: "short-dash",
width: 3
};
// These were const arrays (??)
var coordinatesAx;
var coordinatesAy;
var coordinatesBx;
var coordinatesBy;
// Chane to true after the dialog is open and when modal starts dragging
var moveAlong = false;
var windowElem;
// view.when(function () {
// view.on("pointer-move", showCoordinates);
// });
// NEW: Stop/start moving the modal along with the pointer by map click
// view.when(function(){
// view.on("click", function () { moveAlong = !moveAlong;});
// });
coordinatesAx = -80.96135253906438;
coordinatesAy = 35.9411934679851;
document.getElementById("modal").onclick = function fun() {
windowElem = document.querySelector('.k-window');
// moveAlong = true;
// Bind Kendo dialog dragstart to movement
$("#dialog").data('kendoWindow').bind("dragstart", function (ev) {
//graphicsLayer.removeAll();
moveAlong = true;
console.log("Dragging");
showCoordinates(ev);
document.addEventListener("mousemove", showCoordinates);
}).bind("dragend", function (ev) {
moveAlong = false;
document.removeEventListener("mousemove", showCoordinates);
console.log("end Dragging");
}).bind("close", function (ev) {
console.log("Close. TODO clear line");
})
}
function showCoordinates(evt) {
var point = view.toMap({ x: evt.x, y: evt.y });
var mp = webMercatorUtils.webMercatorToGeographic(point);
dom.byId("info").innerHTML = mp.x.toFixed(3) + ", " + mp.y.toFixed(3);
coordinatesBx = mp.x.toFixed(3);
coordinatesBy = mp.y.toFixed(3);
var polyline = {
type: "polyline",
paths: [
[coordinatesAx, coordinatesAy],
[coordinatesBx, coordinatesBy]
]
};
var polylineGraphic = new Graphic({
geometry: polyline,
symbol: simpleLineSymbol
})
if (moveAlong) {
if (graphicsLayer.graphics.items.length < 0) {
graphicsLayer.add(polylineGraphic)
} else {
// Recreate the line and reposition the modal
graphicsLayer.removeAll();
graphicsLayer.add(polylineGraphic)
}
}
}
});
I have a very strange behaviour of my script: only from time to time (seldom 3-4 times at one time right after each other, but more likely every 7th to 150th trial) the skript loads, but I only see a white canvas and get the error message:
Uncaught TypeError: Cannot read property 'getParent' of
undefinedKonva.Util.addMethods.add # konva.min.js:44draw #
floorplansurvey.php:950(anonymous function) #
floorplansurvey.php:985images.(anonymous function).onload #
floorplansurvey.php:390
On reload it often works again...
I just have no idea at all what is happening here, the bug can't be forced/reproduced, I thank you so much, if you have anything you can help me with. Even a strategy for a clearer analysis would be helpful, sorry for being that unspecific and the long code
edit: I've made a jsfiddle under:
https://jsfiddle.net/17548hmv/1/
run it several times, until the error occures
these are the code snippets at:
# floorplansurvey.php:390:
function loadImages(sources, draw) {
//window.location.reload(true);
var images = {};
var loadedImages = 0;
var numImages = 0;
// get num of sources
for(var src in sources) {
numImages++;
}
for(var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if(++loadedImages >= numImages) {
draw(images);
}
};
images[src].src = sources[src];
}
delete (loadedImages);
delete (numImages);
};
# floorplansurvey.php:985images.(anonymous function).onload:
loadImages(sources, function(images) {
draw(images);
});
# floorplansurvey.php:950(anonymous function):
bglayer.add(plan);
# konva.min.js:44draw:
I dont understand this one myself
add:function(t)
{if(arguments.length>1)
{for(var e=0;e<arguments.length;e++)
this.add(arguments[e]);
return this}if(t.getParent())return t.moveTo(this),this;
var n=this.children;
return
Var sources is defined like:
var sources = {
Cd: './graphics/Cd.png',
Cu: './graphics/Cu.png',
Ca: './graphics/Ca.png',
Cs: './graphics/Cs.png',
Cc: './graphics/Cc.png',
Ed: './graphics/Ed.png',
Eu: './graphics/Eu.png',
Ea: './graphics/Ea.png',
Es: './graphics/Es.png',
Ec: './graphics/Ec.png',
Hd: './graphics/Hd.png',
Hu: './graphics/Hu.png',
...and so on
and this is the function draw:
function draw(images) {
for (i=0, len=showdatax.length; i<=len-1; i++)
{
//window.location.reload(true);
var gridcell = new Konva.Rect({
x: parseInt((imagesizeX - showdatax[i])*scalar-(gridcellsize/2)),
y: parseInt((imagesizeY - showdatay[i])*scalar-(gridcellsize/2)),
offset: [0, 0],
width: gridcellsize,
height: gridcellsize,
//fill: 'white',
//stroke: 'grey',
//strokeWidth: 2,
draggable: false,
id: showdatav[i]
});
gridlayer.add(gridcell);
}
//defaultsettiongs
var init = new Array();
init['x'] = new Array();
init['y'] = new Array();
init['x']['c'] = 0*scalar;
init['y']['c'] = 170*scalar;
init['x']['e'] = 0*scalar;
init['y']['e'] = 320*scalar;
init['x']['h'] = 0*scalar;
init['y']['h'] = 470*scalar;
init['x']['l'] = 0*scalar;
init['y']['l'] = 620*scalar;
init['x']['s'] = 0*scalar;
init['y']['s'] = 770*scalar;
init['x']['w'] = 0*scalar;
init['y']['w'] = 920*scalar; var step = 0;
var count = new Array (
'c','e','h','l','s','w');
count['c'] = 0;
count['e'] = 0;
count['h'] = 0;
count['l'] = 0;
count['s'] = 0;
count['w'] = 0;
var starttime = new Date();
var loghistory = '';
//drag event functions
function mouseoverbox (box,active)
{
writeMessage('Click and hold the left mouse button and pull this activity icon to the floorplan.');
box.setFillPatternImage(active);
box.shadowColor('blue');
box.moveTo(templayer);
badgelayer.draw();
templayer.draw();
}
function dragstarttouchstartbox (box,pos,kind)
{
//count[kind]++;
writeMessage('dragstart' + count[kind]);
var boxx = box.x;
box.x(pos.x-1.5*gridcellsize);
var boxy = box.y;
box.y(pos.y-1.5*gridcellsize);
var boxrshadowoffsetx = box.shadowOffset();
box.shadowOffset({x:0.25*gridcellsize,y:0.25*gridcellsize});
box.moveTo(templayer);
badgelayer.draw();
templayer.draw();
}
function dragmovebox (box,pos,kind,success,active,caution)
{
writeMessage('Your outside of the floorplan. Dropping the activity icon will reset it to its initial position.');
box.moveTo(templayer);
var boxx = box.x;
box.x(pos.x-1.5*gridcellsize);
var boxy = box.y;
box.y(pos.y-1.5*gridcellsize);
var shape = gridlayer.getIntersection(pos);
if (shape)
{
if (!badgelayer.getIntersection(pos))
{
writeMessage('Release the mouse button to place this activity icon on position (' + shape.x() + '|' + shape.y() + ')');
box.x(shape.x()-gridcellsize);
box.y(shape.y()-gridcellsize);
box.setFillPatternImage(success);
box.shadowColor('green');
badgelayer.draw();
}
else
{
writeMessage('Position (' + shape.x() + '|' + shape.y() + ') is in use!!! Can\'t allocate second activiy icon here.');
var boxx = box.x;
box.x(pos.x-1.5*gridcellsize);
var boxy = box.y;
box.y(pos.y-1.5*gridcellsize);
box.setFillPatternImage(caution);
box.shadowColor('red');
badgelayer.draw();
}
}
else
{
box.setFillPatternImage(active);
box.shadowColor('blue');
templayer.draw();
badgelayer.draw();
}
}
function dragendtouchendbox (box,pos,kind,caution,defaultimage)
{
var shape = gridlayer.getIntersection(pos);
box.moveTo(badgelayer);
templayer.draw();
if (shape && !(badgelayer.getIntersection(pos)))
{
writeMessage('Activity icon successfully placed at position (' + shape.x() + '|' + shape.y() + ').');
box.shadowOffset({x:0,y:0});
box.shadowColor('green');
}
else
{
box.shadowColor('red');
box.setFillPatternImage(caution);
badgelayer.draw();
var fromouttween = new Konva.Tween
({
node: box,
x: init['x'][kind]+imagesizeX*scalar+ gridcellsize,
y: init['y'][kind],
easing: Konva.Easings['EaseOut'],
duration: 0.3
});
if (!shape)
{
writeMessage('Please drop the activity icons inside the floorplan.');
}
else if (badgelayer.getIntersection(pos))
{
writeMessage('Please don\'t drop the activity icons onto a used place.');
}
fromouttween.play();
box.shadowColor('black');
box.setFillPatternImage(defaultimage);
box.shadowOffset({x:0,y:0});
badgelayer.draw();
pos.x=-100;
pos.y=-100;
}
count['kind']++;
step++;
writeResultToForm(pos,count,kind,step,loghistory,starttime);
badgelayer.draw();
templayer.draw();
//writeMessage('dragend');
}
function mouseoutbox (box,defaultimage)
{
box.setFillPatternImage(defaultimage);
box.moveTo(badgelayer);
box.shadowColor('black');
if (!validateForm(false))
{
writeMessage('There are still activity icons left to place.');
}
else
{
writeMessage('All activity icons are placed successfully. You can click "continue" now or change your placements.');
}
badgelayer.draw();
templayer.draw();
}
function alertbox (box,caution)
{
box.setFillPatternImage(caution);
box.shadowcolor('red');
badgelayer.draw;
}
//cbox and text
var textc = new Konva.Text({
x: init['x']['c']+imagesizeX*scalar+gridcellsize*5,
y: init['y']['c']+gridcellsize,
text: 'Cooking',
align: 'left',
width: badgetextwidth
});
var boxc = new Konva.Rect({
x: init['x']['c']+imagesizeX*scalar+gridcellsize,
y: init['y']['c'],
offset: [0, 0],
width: 3*gridcellsize,
height: 3*gridcellsize,
fillPatternImage: images.Cd,
fillPatternScaleX: scalar,
fillPatternScaleY: scalar,
stroke: 'black',
strokeWidth: 4,
draggable: true,
cornerRadius: gridcellsize/2,
shadowColor: 'black',
shadowBlur: 10,
shadowOffset: {x : 0, y : 0},
shadowOpacity: 0.5
});
var boxcd = new Konva.Rect({
x: init['x']['c']+imagesizeX*scalar+gridcellsize,
y: init['y']['c'],
offset: [0, 0],
width: 3*gridcellsize,
height: 3*gridcellsize,
fillPatternImage: images.Cu,
fillPatternScaleX: scalar,
fillPatternScaleY: scalar,
stroke: 'grey',
strokeWidth: 2,
draggable: false,
cornerRadius: gridcellsize/2,
});
boxc.on('mouseover ', function() {
mouseoverbox (this,images.Ca);
});
boxc.on('dragstart', function() {
var pos = stage.getPointerPosition();
dragstarttouchstartbox (this,pos,'c');
});
boxc.on('dragmove', function () {
var pos = stage.getPointerPosition();
dragmovebox(this,pos,'c',images.Cs,images.Ca,images.Cc);
});
boxc.on('dragend', function() {
var pos = stage.getPointerPosition();
dragendtouchendbox (this,pos,'c',images.Cc,images.Cd);
});
boxc.on('mouseout ', function() {
mouseoutbox (this,images.Cd)
});
boxc.on('foo', function() {
alertbox (this,images.Cd)
});
//ebox and text
var texte = new Konva.Text({
x: init['x']['e']+imagesizeX*scalar+gridcellsize*5,
...and so on for all the boxes addes here (5 times as long):
defaultlayer.add(boxcd);
badgelayer.add(boxc);
defaultlayer.add(textc);
defaultlayer.add(boxed);
badgelayer.add(boxe);
defaultlayer.add(texte);
defaultlayer.add(boxhd);
badgelayer.add(boxh);
defaultlayer.add(texth);
defaultlayer.add(boxld);
badgelayer.add(boxl);
defaultlayer.add(textl);
defaultlayer.add(boxsd);
badgelayer.add(boxs);
defaultlayer.add(texts);
defaultlayer.add(boxwd);
badgelayer.add(boxw);
defaultlayer.add(textw);
stage.add(bglayer);
stage.add(gridlayer);
stage.add(defaultlayer);
stage.add(badgelayer);
stage.add(templayer);
}
OK, sorry that it took me so long:
the solution wasn't that easy to find. I found that the script was loaded asynchronously and the png wasn't yet available by using chromes timeline analysis. so i went to my code and had to distinguish between the things, that really should be in the draw function and which not. i added the plan to the array of images (sources) that is loaded (src= ...) before executing draw() and then added
sources.onload= loadImages(sources, function(images) {
draw(images);
});
at the end of my file... no it works without any problem. konva.js had nothing to do with it and is up to now (I'm almost ready) like designed for my project
thanks for the tip #lavrton, it took me on the right way
and you can just put like this:
var imageObj = new Image();
imageObj.src = 'http://localhost:8000/plugins/kamiyar/logo.png';
imageObj.onload = function() {
var img = new Konva.Image({
image: imageObj,
x: stage.getWidth() / 2 - 200 / 2,
y: stage.getHeight() / 2 - 137 / 2,
width: 200,
height: 137,
draggable: true,
stroke: 'blue',
strokeWidth: 1,
dash: [1,5],
strokeEnabled: false
});
layer.add(img);
layer.draw();
};
sorry for my bad English ;)
I've finally got my nodes almost done perfectly, unfortunately I'm having one more problem
the width of what is drawn on the canvas isn't the width of the defined node. The blue + purple is the node div + padding, and I could perfectly center it using that if it weren't for the fact that what is drawn doesn't care about the width I have for that. Here's my code for my spacetree:
function jitSpaceTree(data,index,rootid){
var json = eval("(" + data + ")");
console.log(json);
//end
//init Spacetree
//Create a new ST instance
var st = new $jit.ST({
//id of viz container element
injectInto: 'hier'+index,
//set duration for the animation
duration: 800,
//set animation transition type
transition: $jit.Trans.Quart.easeInOut,
//set distance between node and its children
levelDistance: 25,
orientation: 'top',
//enable panning
Navigation: {
enable:true,
panning:true
},
//set node and edge styles
//set overridable=true for styling individual
//nodes or edges
Node: {
autoHeight: true,
autoWidth: true,
type: 'rectangle',
color: '#aaa',
overridable: true
},
Edge: {
type: 'bezier',
overridable: true
},
//This method is called on DOM label creation.
//Use this method to add event handlers and styles to
//your node.
onCreateLabel: function(label, node){
label.id = node.id;
label.innerHTML = node.name;
label.onclick = function(){
st.onClick(node.id);
st.select(node.id);
st.removeSubtree(label.id, false, "replot", {
hideLabels: false
});
jQuery.getJSON('Mobile_Subordinate.cfm?Empid='+node.id, function(data2) {
var subtree = '';
for(var i=0; i<data2.DATA.length-1; i++){
subtree = subtree + '{"id": "' + data2.DATA[i][4].replace(/\s/g, '') + '","name": "' + data2.DATA[i][0].replace(/\s/g, '') + '<br>' + data2.DATA[i][1].replace(/\s/g, '') + '","data": {},"children": []},';
}
subtree = subtree + '{"id": "' + data2.DATA[data2.DATA.length-1][4].replace(/\s/g, '') + '","name": "' + data2.DATA[data2.DATA.length-1][0].replace(/\s/g, '') + '<br>' + data2.DATA[data2.DATA.length-1][1].replace(/\s/g, '') + '","data": {},"children": []}';
subtree = '{"id": "'+label.id+'", "children": ['+ subtree +']}'
childData = jQuery.parseJSON(subtree);
console.log(childData);
st.addSubtree(childData, 'replot',{
hideLabels: false
});
});
};
//set label styles
var style = label.style;
style.width = node.data.offsetWidth;
style.height = node.data.offsetHeight;
style.cursor = 'pointer';
style.color = '#fff';
style.fontSize = '0.8em';
style.textAlign= 'center';
},
//This method is called right before plotting
//a node. It's useful for changing an individual node
//style properties before plotting it.
//The data properties prefixed with a dollar
//sign will override the global node style properties.
onBeforePlotNode: function(node){
//add some color to the nodes in the path between the
//root node and the selected node.
if (node.selected) {
node.data.$color = "#ab8433";
}
else {
delete node.data.$color;
node.data.$color = "#ccc";
}
},
//This method is called right before plotting
//an edge. It's useful for changing an individual edge
//style properties before plotting it.
//Edge data proprties prefixed with a dollar sign will
//override the Edge global style properties.
onBeforePlotLine: function(adj){
if (adj.nodeFrom.selected && adj.nodeTo.selected) {
adj.data.$color = "#eed";
adj.data.$lineWidth = 3;
}
else {
delete adj.data.$color;
delete adj.data.$lineWidth;
}
}
});
//load json data
st.loadJSON(json);
//compute node positions and layout
st.compute();
//optional: make a translation of the tree
st.geom.translate(new $jit.Complex(-200, 0), "current");
//emulate a click on the root node.
//st.onClick(st.root);
st.onClick(rootid);
//end
}
What am I missing?
Not an exact answer but could this be a padding issue?
I know from my own experience that
Node: {
height: 80,
width: 140
}
needs...
{style.width = 136 + 'px';
style.height = 75 + 'px';
style.paddingTop = '5px';
style.paddingLeft = '2px';
style.paddingRight = '2px';}
to center align.
I wonder if there is a default padding you're missing?
Im currently developing an web application which includes google maps. Im developing using Jquery and a lib called GMAP3. You can take a look here if you want. http://gmap3.net/
I've created a driving direction function and also an radius circle function. Im using an javascript menu to run the functions. You can for example place the orgin position with right clicking on that position and chose place orgin position using a menu. That part works correctly. A marker is added to that position and also a circle which centers from that position. BUT, if im moving the driving direction destination marker the circle still stays on its place. I do really need some help with this. Thanks.
Javascript code:
/**************************************************
* Menu
**************************************************/
function Menu($div){
var that = this,
ts = null;
this.$div = $div;
this.items = [];
// create an item using a new closure
this.create = function(item){
var $item = $('<div class="item '+item.cl+'">'+item.label+'</div>');
$item
// bind click on item
.click(function(){
if (typeof(item.fnc) === 'function'){
item.fnc.apply($(this), []);
}
})
// manage mouse over coloration
.hover(
function(){$(this).addClass('hover');},
function(){$(this).removeClass('hover');}
);
return $item;
};
this.clearTs = function(){
if (ts){
clearTimeout(ts);
ts = null;
}
};
this.initTs = function(t){
ts = setTimeout(function(){that.close()}, t);
};
}
// add item
Menu.prototype.add = function(label, cl, fnc){
this.items.push({
label:label,
fnc:fnc,
cl:cl
});
}
// close previous and open a new menu
Menu.prototype.open = function(event){
this.close();
var k,
that = this,
offset = {
x:0,
y:0
},
$menu = $('<div id="menu"></div>');
// add items in menu
for(k in this.items){
$menu.append(this.create(this.items[k]));
}
// manage auto-close menu on mouse hover / out
$menu.hover(
function(){that.clearTs();},
function(){that.initTs(3000);}
);
// change the offset to get the menu visible (#menu width & height must be defined in CSS to use this simple code)
if ( event.pixel.y + $menu.height() > this.$div.height()){
offset.y = -$menu.height();
}
if ( event.pixel.x + $menu.width() > this.$div.width()){
offset.x = -$menu.width();
}
// use menu as overlay
this.$div.gmap3({
action:'addOverlay',
latLng: event.latLng,
content: $menu,
offset: offset
});
// start auto-close
this.initTs(5000);
}
// close the menu
Menu.prototype.close = function(){
this.clearTs();
this.$div.gmap3({action:'clear', name:'overlay'});
}
/**************************************************
* Main
**************************************************/
$(function(){
var $map = $('#googleMap'),
menu = new Menu($map),
current, // current click event (used to save as start / end position)
m1, // marker "from"
m2, // marker "to"
center = [48.85861640881589, 2.3459243774414062];
// update marker
function updateMarker(marker, isM1){
if (isM1){
m1 = marker;
} else {
m2 = marker;
}
updateDirections();
}
function Startdistancewidget()
{
$map.gmap3({
action: 'addCircle',
circle:{
options:{
center: current.latLng,
radius : 75000,
fillColor : "Green",
strokeColor : "White"
}
}
})
}
function Finishdistancewidget()
{
$map.gmap3({
action: 'addCircle',
circle:{
options:{
center: current.latLng,
radius : 75000,
fillColor : "Red",
strokeColor : "White"
}
}
})
}
// add marker and manage which one it is (A, B)
function addMarker(isM1){
// clear previous marker if set
var clear = {action:'clear', name:'marker', tag:''};
if (isM1 && m1) {
clear.tag = 'from';
$map.gmap3(clear);
} else if (!isM1 && m2){
clear.tag = 'to';
$map.gmap3(clear);
}
// add marker and store it
$map.gmap3({
action:'addMarker',
latLng:current.latLng,
options:{
draggable:true,
icon:new google.maps.MarkerImage('images/icon_big_' + (isM1 ? 'start' : 'stop') + '.png')
},
tag: (isM1 ? 'from' : 'to'),
events: {
dragend: function(marker){
updateMarker(marker, isM1);
}
},
callback: function(marker){
updateMarker(marker, isM1);
}
});
}
// function called to update direction is m1 and m2 are set
function updateDirections(){
if (!(m1 && m2)){
return;
}
$map.gmap3({
action:'getRoute',
options:{
origin:m1.getPosition(),
destination:m2.getPosition(),
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
callback: function(results){
if (!results) return;
$map.gmap3({ action: 'setDirections', directions:results});
}
});
}
// MENU : ITEM 1
menu.add('Allign start position here', 'itemA',
function(){
menu.close();
addMarker(true);
Startdistancewidget();
});
// MENU : ITEM 2
menu.add('Allign checkpoint position here', 'itemB',
function(){
menu.close();
addMarker(false);
})
// MENU : ITEM 3
menu.add('Allign finish position here', 'itemC separator',
function(){
menu.close();
addMarker(false);
Finishdistancewidget();
})
// MENU : ITEM 4
menu.add('Zoom in', 'zoomIn',
function(){
var map = $map.gmap3('get');
map.setZoom(map.getZoom() + 1);
menu.close();
});
// MENU : ITEM 5
menu.add('Zoom out', 'zoomOut',
function(){
var map = $map.gmap3('get');
map.setZoom(map.getZoom() - 1);
menu.close();
});
// MENU : ITEM 6
menu.add('Center here', 'centerHere',
function(){
$map.gmap3('get').setCenter(current.latLng);
menu.close();
});
// INITIALIZE GOOGLE MAP
$map.gmap3(
{ action: 'init',
options:{
center:center,
zoom: 5
},
events:{
rightclick:function(map, event){
current = event;
menu.open(current);
},
click: function(){
menu.close();
},
dragstart: function(){
menu.close();
},
zoom_changed: function(){
menu.close();
}
}
},
// add direction renderer to configure options (else, automatically created with default options)
{ action:'addDirectionsRenderer',
preserveViewport: true,
markerOptions:{
visible: false
}
},
// add a direction panel
{ action:'setDirectionsPanel',
id : 'directions'
}
);
});
I do not know what would be the syntax for that in gmap3 plugin but you have to bind circle to your marker if you want it to be repositioned if marker is dragged. In google API it is
circle.bindTo('center', marker, 'position');
I am doing almost the same thing right now.