Repository navigation
Expand file tree
/
Copy pathplugin.js
More file actions
292 lines (236 loc) · 11 KB
/
Copy pathplugin.js
File metadata and controls
292 lines (236 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
(function() {
const constants = {
apiTimeout: 25,
convertMetersToFeet: 1,
notificationHandle: undefined
}
/**
* Get the numeric value of an input element. Defaults to 1.
* @param {string} id - The id of the input element
* @returns {number}
*/
const getInputNumberById = id => {
const element = document.getElementById(id)
const value = element !== null ? element.value : 0
const number = Number(value)
if(isNaN(number) || number === 0)
throw `Failed to get input value of element #${id}`
return number
}
/**
* Create 3D context
*/
const create3DContext = async () => {
try {
// Get location info from FormIt
await updateCoordinatesFromLocation()
constants.notificationHandle = displayGeneralMessage('Získané souřadnice z nastavení umístění')
// Disable 'Create' button until current operation is completed
document.getElementById("CreateButton").disabled = true
// Create an object of all the HTML <input> values
const inputs = {
latitude: getInputNumberById("Latitude"),
longitude: getInputNumberById("Longitude"),
radius: getInputNumberById("Radius")
}
// https://www.openstreetmap.org/#map=17/51.50111/-0.12531
const locationGeoPoint = turf.point([ inputs.longitude,inputs.latitude ])
const locationGeoBbox = getBbox(locationGeoPoint, inputs.radius)
// Get the data from the OpenStreetMaps API
const osmData = await getOSMData(locationGeoBbox)
// Convert the OpenStreetMaps data to GeoJSON
const geoJsonData = osmtogeojson(osmData)
const geoFeatures = geoJsonData.features.filter(feature => feature.geometry.type === "Polygon" )
// Create FormIt geometry
createFormItGeometry(geoFeatures, locationGeoPoint)
document.getElementById("CreateButton").disabled = false
}
catch (e) {
displayErrorMessage("An error has occured. " + e)
console.error("An error has occured", e)
document.getElementById("CreateButton").disabled = false
}
}
/**
* Get the bounding box around the origin
* @param {Object} locationGeoPoint - GeoJSON location point
* @returns {Object} A turf.js bounding box
*/
const getBbox = (locationGeoPoint, radius) => {
const circle = turf.circle(locationGeoPoint, radius * 0.001, { steps: 4 })
return turf.bbox(circle)
}
/**
* OpenStreetMap® data was used to generate this plugin: https://www.openstreetmap.org/copyright
* @param {Object} bbox - Bounding box
* @returns {Object} The OSM response as an awaitable JSON object
*/
const getOSMData = async (bbox) => {
const filters = [ "building" ]
const endpoint = "https://overpass-api.de/api/interpreter"
const bounds = `${bbox[1]},${bbox[0]},${bbox[3]},${bbox[2]}`
let query = `?data=[out:json][timeout:${constants.apiTimeout}][bbox:${bounds}];`
if (filters.length > 0) {
query += "("
filters.forEach(filter => {
query += `way[${filter}];`
query += `relation[${filter}];`
})
query += ");"
}
query += "(._;>;);"
query += "out;"
const url = endpoint + query
displayWarningMessage(`Odeslán API požadavek. V závislosti na informacích a poloměru čtverce to může trvat až ${constants.apiTimeout} sekund`)
const response = await fetch(url)
if(response.ok)
return response.json()
throw `API request failed. ${response.status} ${response.statusText}`
}
/**
* Create FormIt geometry
* @param {Array} features - An array of GeoJSON features
* @param {Object} center - GeoJSON location point
* @returns {Array} FormIt extrusions
*/
const createFormItGeometry = async (features, center) => {
// Create a new history ID and store it in the plugin state object
const historyID = await FormIt.GroupEdit.GetEditingHistoryID()
//Create group for the context group under current history ID
const allContextGroupID = await WSM.APICreateGroup(historyID, [])
//History ID for the context group
const allContextGroupHistoryID= await WSM.APIGetGroupReferencedHistoryReadOnly(historyID, allContextGroupID)
// Loop through each feature
const geometryFormIt = Promise.all(features.map(async feature => {
const storeyHeight = 12 //12 feet (average floor size)
let height = storeyHeight
if(feature.properties.building !== void 0)
height = feature.properties.height
if(feature.properties["building:levels"] !== void 0)
height = feature.properties["building:levels"] * storeyHeight
else
height = storeyHeight
// Convert each GeoJSON polygon to an array of FormIt points
const polygonsFormIt = feature.geometry.coordinates.map(async (polygon, index,points) =>
{
return Promise.all(polygon.map( vertex =>
{
const vertexFeet = CoordinateLocationToFeet(vertex,center.geometry.coordinates)
return WSM.Geom.Point3d(vertexFeet[0], vertexFeet[1], 0)
}))
})
//start undo manager state - this should suspend WSM and other updates to make this faster
FormIt.UndoManagement.BeginState()
//empty group in main group history
const groupID = await WSM.APICreateGroup(allContextGroupHistoryID,[])
//history of the group, history to put buildings into
const groupHistoryID = await WSM.APIGetGroupReferencedHistoryReadOnly(allContextGroupHistoryID , groupID)
//connect each of these points in the array into a polyline
await Promise.all(polygonsFormIt.map(async (points, index) => {
try {
const allPts = await points
for(let i=0;i< allPts.length;i++)
{
let k = (i + 1 + allPts.length) % allPts.length
//sketch all out into group history
const pl = WSM.APIConnectPoint3ds(groupHistoryID, allPts[i], allPts[k])
}
}
catch (e) {
throw 'Failed to create extrusion'
}
}))
//get all faces generated by polylines
const faces = await WSM.APIGetAllObjectsByTypeReadOnly(groupHistoryID, WSM.nObjectType.nFaceType)
//drag or extrude only the first face generated by all polylines according to height
await WSM.APIDragFace(groupHistoryID, faces[0], height)
//delete inner loop faces
faces.forEach(async f =>
{
const index = faces.indexOf(f)
if(index !== 0)
{
await WSM.APIDeleteObject(groupHistoryID,faces[index])
}
})
FormIt.UndoManagement.EndState("Created geometry")
}))
displaySuccessMessage(`Vytvořeno ${(await geometryFormIt).length} prvků`)
}
const CoordinateLocationToFeet = (point, origin)=>
{
const pointX = turf.point([point[0], origin[1]])
const pointY = turf.point([origin[0], point[1]])
const options = {units: 'feet'};
let distanceX = turf.distance(origin, pointX, options)
let distanceY = turf.distance(origin, pointY, options)
if (point[0]<origin[0]) distanceX = -distanceX
if (point[1]<origin[1]) distanceY = -distanceY
const coordinates = [distanceX,distanceY]
return coordinates
}
/**
* Find coordinates from address set by users
*/
const updateCoordinatesFromLocation = async()=>
{
//Get location info from FormIt
const location = await FormIt.SunAndLocation.GetLocationDateTime()
const lat = location.latitude
const long = location.longitude
//update latitude and longitude to UI input field
document.getElementById("Latitude").value = lat
document.getElementById("Longitude").value = long
}
/**
* Update bubble text on range slider
*/
const allRanges = document.querySelectorAll(".range-wrap")
allRanges.forEach(wrap =>
{
const range = wrap.querySelector(".range")
const bubble = wrap.querySelector(".bubble")
range.addEventListener("input", () =>
{
setBubble(range, bubble)
})
setBubble(range, bubble)
})
function setBubble(range, bubble)
{
const val = range.value
const min = range.min ? range.min : 0
const max = range.max ? range.max : 100
const newVal = Number(((val - min) * 100) / (max - min))
bubble.innerHTML = val
// Sorta magic numbers based on size of the native UI thumb
bubble.style.left = `calc(${newVal}% + (${8 - newVal * 0.15}px))`
}
// Show messages with FormIt popUp
const displayGeneralMessage = async message =>
{
await FormIt.UI.CloseNotification(constants.notificationHandle)
constants.notificationHandle = undefined
constants.notificationHandle = await FormIt.UI.ShowNotification(message, FormIt.NotificationType.Information, 1 );
}
const displayWarningMessage = async message =>
{
await FormIt.UI.CloseNotification(constants.notificationHandle)
constants.notificationHandle = undefined
constants.notificationHandle = await FormIt.UI.ShowNotification(message, FormIt.NotificationType.Warning, 0);
}
const displayErrorMessage = async message =>
{
await FormIt.UI.CloseNotification(constants.notificationHandle)
constants.notificationHandle = undefined
constants.notificationHandle = await FormIt.UI.ShowNotification(message, FormIt.NotificationType.Error, 0);
}
const displaySuccessMessage = async message =>
{
await FormIt.UI.CloseNotification(constants.notificationHandle)
constants.notificationHandle = undefined
constants.notificationHandle = await FormIt.UI.ShowNotification(message, FormIt.NotificationType.Success, 0);
}
// Trigger execute when the create button is clicked
document.getElementById("CreateButton").addEventListener("click", create3DContext)
}());