Access to polygon matrix from json files - google-maps

I load polygons from json file using loadGeoJson. In json file I have properties name and id. All Polygons loads correctly on the map.
How can I get matrix of all polygons? I need to check that my point containsLocation of one from this polygons. TIA 4 answer

I use :
var woj =[];
map.data.addListener('addfeature', function(event) {
var adm=event.feature.getProperty('id');
woj.push(adm);
});
That solves my problem.

Related

Loading geoJSON to Cesium does not work but I get no errors

I try to pass data from PostGIS to Cesium, I believe the simpler way is to use GeoJSON.
To test it I do a query to my PostGIS to get some geoJSON data
SELECT ST_AsGeoJSON(mygeom)
FROM mytable where id = 370;
then I copy the result to a cesium sandcastle to see how it works
var viewer = new Cesium.Viewer('cesiumContainer');
const greenPolygon = viewer.entities.add({
name: "Green extruded polygon",
polygon: {
hierarchy : Cesium.GeoJsonDataSource.load({"type":"MultiPolygon","coordinates":[[[[386788.842267334,4204512.29371444],[386804.47751787,4204512.29371444],[386804.47751787,4204510.66293459],[386788.854170836,4204510.66293459],[386788.842267334,4204512.29371444]]]]}),
extrudedHeight: 100000.0,
material: Cesium.Color.YELLOW.withAlpha(0.5),
outline : true,
outlineColor : Cesium.Color.BLACK,
closeTop: true,
closeBottom: true
},
});
viewer.zoomTo(viewer.entities);
I get no errors in the cesium sandcastle console, but I also see no polygon on the map. The geometry in my PostGIS table is geometry(MultiPolygon,2100), I dont know if this is the issue.
Please advice
Thanks
CesiumJS will not understand your coordinates(ex 386788.842267334,4204512.29371444) defined in your custom spatial reference system.
You must specify coordinates using geographic latitude, and longitude.

Save and retrive in forge viewer

I am using forge viewer for displaying AutoCAD files.
Also using the drawing tool over viewer based on the sample source.
I will draw the area by using box or sphere draw tools.
I need to save the current viewer including box or sphere area which I was marked over viewer and when again loading same file the area which has been marked that should be bind default.
How it is possible please help me
Suggest any way to implement this scenario.
Thanks in advance.
You can do that with 2 steps.
First, taking advantage of Object3D.toJSON() method.
Let's summarize in a sample where we generate a JSON object from our mesh:
//here we create a BoxGeometry
let geom = new THREE.BufferGeometry().fromGeometry(new THREE.BoxGeometry(100,100,100));
let phongMaterial = new THREE.MeshPhongMaterial({
color: new THREE.Color(1, 0, 0)
});
let mesh = new THREE.Mesh(geom, phongMaterial);
if (!viewer.overlays.hasScene("CustomScene")) {
viewer.overlays.addScene("CustomScene");
}
viewer.overlays.addMesh(mesh, "CustomScene");
viewer.impl.sceneUpdated(true);
//here we generate the JSON from the mesh and download it
let jsonObject = JSON.stringify(mesh.toJSON())
download(jsonObject, 'Box.json', 'text/plain');
download function can be found here.
The next step is about generating the box from the saved JSON.
For that, we'll use ObjectLoader.parse method.
And again, we can summarize in the code below:
//here we read the JSON object from our generated file
var request = new XMLHttpRequest();
request.open("GET", "js/Box.json", false);
request.send(null)
var my_JSON_object = JSON.parse(request.responseText);
//here we generate the mesh
let mesh = new THREE.ObjectLoader().parse(my_JSON_object);
if (!viewer.overlays.hasScene("CustomScene")) {
viewer.overlays.addScene("CustomScene");
}
viewer.overlays.addMesh(mesh, "CustomScene");
viewer.impl.sceneUpdated(true);
Refer here for the function to read objects from JSON file.

Can't import geojson value as string in google maps with firebase web

So, I set up my firebase to communicate with my web app which uses google maps api and my goal is this: When a user draws a shape on the map(polygon, linestring), I want to send the geoJson value of it to the firebase(currently sending it as a String), and then retrieve it back so it appears on the map for everyone(since it's getting synced from the firebase database). My problem is that when I try to retrieve the geoJson data back and add it on google maps, at the line map.data.addGeoJson(geoJsonString);(geoJsonString = geoJson value that is stored in firebase) I get an error saying:
Uncaught Jb {message: "not a Feature or FeatureCollection", name: "InvalidValueError", stack: "Error↵ at new Jb (https://maps.googleapis.com/m…tatic.com/firebasejs/4.13.0/firebase.js:1:278304)"}
For some reason google maps api doesnt accept the geoJson value even though console.log(geoJsonString); returns a valid geoJson value (checked at http://geojsonlint.com/)
Now the strange part is that if I try to import the same geoJson value manually(storing the geoJson value in a var and then map.data.addGeoJson(geoJsonString);) it works just fine.
This function syncs firebase with the web app
function gotData(data){
paths = data.val();
if(paths == null){
console.log("firebase null");
alert('Database is empty! Try adding some paths.');
}
else{
var keys = Object.keys(paths);
for(var i = 0; i < keys.length; i++){
var k = keys[i];
var geoJsonString = paths[k].geoJsonString;
console.log(geoJsonString);
map.data.addGeoJson(geoJsonString);
}
}
}
This function updates and pushes data in firebase
function updateData(){
data = {
geoJsonString: geoJsonOutput.value
}
ref = database.ref('firebasePaths');
ref.push(data);
}
In this function(which is used to store geoJson values locally in a file), I call updateData function), after a new path is drawn on the map
// Refresh different components from other components.
function refreshGeoJsonFromData() {
map.data.toGeoJson(function(geoJson) {
geoJsonOutput.value = JSON.stringify(geoJson);
updateData();
refreshDownloadLinkFromGeoJson();
});
}
Example of my firebase that contains 2 random geoJson
I can't trace where the problem is. Any ideas?
Update: I managed to fix this issue by parsing the string with JSON.parse("retrieved string from firebase"), saving it to a variable and then adding it to the map with map.data.addgeoJson(parsed variable).
We still have not faced that issue, however, we are aware of it.
Our intended solution is to use GeoFire: An open-source library for the Firebase Realtime Database that adds support for geospatial querying.
You can find the library description in here:
https://firebase.google.com/docs/libraries/
For the Web supported library:
https://github.com/firebase/geofire-js

Database instead of kml file

I wonder, is it possible to connect a db to google maps api to render polygons, points etc?
If a store all kml coordinates connected to polygons, will it be possible to render it fra database or do i need to create a kml file to visualize it?
Is there any example?
Thanks!
A KML file is not required to visualize points, polygons, etc using Google Maps API. However, the KML layer is a useful way to represent complex geospatial features.
A backend database with HTTP access could return a list of map coordinates that your client code can render into appropriate shapes using Google Maps API.
The Google Maps API provides examples to create various shapes.
Example to create simple point marker:
https://developers.google.com/maps/documentation/javascript/examples/marker-simple
Example to create simple polygon:
https://developers.google.com/maps/documentation/javascript/examples/polygon-simple
The client code will need to query the data from the database such as from a servlet with access to the database. Database will most likely be running on a different port or from a different server so javascript won't be able to access it directly.
Your server-side component could query a database and return formatted KML or it could return a JSON result that your client code would render. Depends on whether you want to write more backend server code or JavaScript code on the client.
hmmm... I am using another solution now (data from DB to show on Google earth which is default application for KML file) and hope this help :
( may refer to https://sites.google.com/site/canadadennischen888/home/kml/auto-refresh-3d-tracking )(plus, in my other page, there is sample java code)
Details as :
prepare a RestFul service to generate KML file from DB (KML sample as inside above link)
My other jsp code will generate a KMZ file which has a link to my Restful service. KMZ file has onInterval ( as in the bottom)
Jsp web page allow user to download KMZ file.
When Google Earth open KMZ file, Google Earth will auto refresh to get new data from that Restful service
Everytime refreshing, server will send the latest update KML data with new data to GE.
KMZ sample:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2"
xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<NetworkLink>
<name>Dennis_Chen_Canada#Hotmail.com</name>
<open>1</open>
<Link>
<href>http://localhost:9080/google-earth-project/rest/kml/10001/20002</href>
<refreshMode>onInterval</refreshMode>
</Link>
</NetworkLink>
</kml>
result as :
Thanks for you're answer. I don't know if i get somewhat wiser of this, but at least i know that it is possible.
I have used Shape2Sql to save the coordinates in the database.
But as i understand, i need someway to convert this to geojson before it can render in Google maps? if i understand correct?
As i understand to render geojson is mostly the same as to render kml when it comes to files. But i don't know how to Connect to a database.
I make a list from database:
var adresses = _unitOfWork.GeoAddressRepository.Get(q => q.GeoRouteNorpost.Code == "3007106", includeProperties: "GeoRouteNorpost").ToList();
var points = new List<LatLong>();
foreach (var address in adresses)
{
points.Add(new LatLng() { Lat = "59.948261", Lng = "10.750699" });
points.Add(new LatLng() { Lat = "59.943128", Lng = "10.755814" });
points.Add(new LatLng() { Lat = "59.941245", Lng = "10.746084" });
points.Add(new LatLng() { Lat = "59.943527", Lng = "10.742786" });
points.Add(new LatLng() { Lat = "59.946824", Lng = "10.744435" });
points.Add(new LatLng() { Lat = "59.946813", Lng = "10.744446" });
points.Add(new LatLng() { Lat = "59.947107", Lng = "10.748241" });
points.Add(new LatLng() { Lat = "59.947827", Lng = "10.749525" });
points.Add(new LatLng() { Lat = "59.948248", Lng = "10.750699" });
}
This example show a polygon on a map. But i'm not sure how to get this coordinates out of the database and how to solve it when it is serveral polygons.
As i have written, i have saved the coordinates in the db With shape2Sql. So now i have a Field for geometry. If i look at the spatial result in sql server this looks correct. But how can i display this in Google maps?
I am grateful for all help:)

Accessing a placemark with google earth api through Region-Based Network Linked kml files

I have a huge set of placemarks loaded using regionated kml files. (around 1000 kml files generated).
For example , I have a button, when clicked camera flies to the location of the placemark I want to access. So I think the kml file that includes this placemark is loaded after this process. Let's say this is 5.kml and I tried to get the placemark object using getElementByUrl method. But this didn't work. I can also use ge.getElementsByType("KmlPlacemark") method but I need to have a loop to get the placemark object I need. This works but I couldn't find a way to make it work fast. Below is my code
google.earth.addEventListener(ge.getView(), 'viewchangeend', function() {
// after button click and camera centered on the placemark with id 1767
var p = ge.getElementByUrl('http://localhost/Test/5.kml#1767');
alert(p.getId()); // this does not work because p is null
var placemarks = ge.getElementsByType('KmlPlacemark');
for (var i = 0; i < placemarks.getLength(); ++i) {
var placemark = placemarks.item(i);
if(placemark.getId() == 1767)
{
alert(placemark.getId()); // this works
return;
}
}
});
function button_click()
{
var camera = ge.getView().copyAsCamera(ge.ALTITUDE_RELATIVE_TO_GROUND);
camera.setLatitude(30);
camera.setLongitude(50);
camera.setAltitude(2000);
ge.getView().setAbstractView(camera);
}
I wish I found a way to access the object which is imported from KML(when region beomes active). Waiting for your answers. Thanks.
NetworkLink's don't load files into the DOM, which is why getElementByUrl doesn't find the Placemark you're looking for. You would need to fetch the KML. This article should be helpful in explaining the different ways to load KML in the Google Earth API.