Proper way to use ReferencedEnvelope - geotools

Using examples I found, I was able to connect to a webservice, download a world map and have it display properly in a JMapPane. My goal is to have the JMapPane only display a very specific portion of the world.
I have a geographic CRS based on NAD83 and UTM 17N. I prefer to use Northing and Easting values, for which I have the bounds of the area I wish to display.
Here is the relevant code:
Rectangle bounds=projectdata.getPlanRange();
ReferencedEnvelope envelope = new ReferencedEnvelope(bounds.getMinX(), bounds.getMaxX(), bounds.getMinY(), bounds.getMaxY(), projectdata.getWorkPlancrs());
mapPane.setDisplayArea(envelope);
If I don't set the displayarea with the envelope, I see the world. If I set it, it gives me a view of water somewhere in the world. I can only assume that the ReferencedEnvelope can handle Northing/Easting values with a geographic CRS provided. I've read the documentation a few times and searched a long time before posting this question. I'm sure there is a simple answer as to what I'm doing wrong.
In case it matters at all, the wms source I am using is
http://atlas.gc.ca/cgi-bin/atlaswms_en?VERSION=1.1.1&Request=GetCapabilities&Service=WMS

You don't say how you are creating your map in the JFrame. But the following works for me (subject to some caveats I'll go into below). The trick is to set the viewport with the CRS and the Bounding Box you require. You can get the full code here.
private void createWMS() {
content.getViewport().setCoordinateReferenceSystem(crs);
content.getViewport().setBounds(bbox);
if (url == null) {
throw new IllegalStateException("URL is not set");
}
try {
wms = new WebMapServer(url);
} catch (ServiceException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(2);
}
WMSCapabilities capabilities = wms.getCapabilities();
org.geotools.data.ows.Layer[] wmsLayers = WMSUtils.getNamedLayers(capabilities);
for (org.geotools.data.ows.Layer wmsLayer : wmsLayers) {
if(layers.isEmpty()) {//just write out layers
System.out.println(wmsLayer.getName());
}
if (layers.contains(wmsLayer.getName())) {
WMSLayer displayLayer = new WMSLayer(wms, wmsLayer);
if (!styles.isEmpty()) {
String wmsStyle = styles.get(layers.indexOf(wmsLayer.getName()));
displayLayer = new WMSLayer(wms, wmsLayer);
List<StyleImpl> layerStyles = wmsLayer.getStyles();
for (StyleImpl s : layerStyles) {
if (s.getName().equalsIgnoreCase(wmsStyle)) {
displayLayer.setStyle((Style) s);
}
}
}
content.addLayer(displayLayer);
}
}
}
This produces with the CRS set to EPSG:26917 and a bbox of roughly -157051,5400992, 279239,5664905 of a map like:
As you can see this service is ending soon! and also it doesn't handle EPSG:26917 very well as it has drawn the "back" of Russia on the other side of the globe and labelled it before drawing Canada which is a bit confusing and if you zoom out much further the map becomes unusable due to the borders and rivers etc crossing "behind" the map.

Related

Is It possible to move the avatar programmatically or specify position in Autodesk.AEC.Minimap3DExtension

Autodesk.AEC.Minimap3DExtension provides a 3d and 2d sync forge viewer where a user can use 2d viewer and move the avatar to navigate. In order to navigate user has to move the avatar or a dot icon in 2d viewer to navigate in 3d model.
My question is where is there any possibility where I can send the set of coordinates which are with me and can I move the avatar programmatically so that user don't have to do so.
here is any example why I am asking so,
I have a geometry on my forge viewer which is on 2D and I am looking to make a first person view over that geometry.
So If I have all the points of geometry I want to make it use with Autodesk.AEC.Minimap3DExtension so that I can move first person to different views
here is the sample I am rereferring to link
I had been following this wonderful blog link
with the help of this I am aware little bit aware how to work with 2dto3d
here in above link
const worldPos = sheetToWorld(intersection.intersectPoint, viewer2D.model,
viewer3D.model);
the above line of code gives me worldPos with which a geometric point is
created in the 3d viewer in spite of creating a geometry how can I use to
show view of that particular place
basically in this below line of code which transits camera from one position to another
viewer.navigation.setRequestTransition(true, newPos, newTarget,
viewer.navigation.getHorizontalFov());
I'm glad you like the blog post :)
After reading the question I have the impression that you have already answered it yourself. If you have some kind of a geometry, let's say a polyline, overlaid on top of the 2D drawing, you can use the same logic explained in the blog post, but when calling viewer.hitTest, instead of passing in some mouse coordinates, you would just supply one of the points of your polyline.
Instead of:
viewer2D.container.addEventListener('click', function (ev) {
const intersection = viewer2D.hitTest(ev.clientX, ev.clientY);
viewer3D.isolate([]);
if (intersection) {
viewer3D.isolate(intersection.dbId);
const worldPos = sheetToWorld(intersection.intersectPoint, viewer2D.model, viewer3D.model);
if (worldPos) {
let mesh = new THREE.Mesh(geometry, material);
mesh.position.set(worldPos.x, worldPos.y, worldPos.z);
viewer3D.overlays.addMesh(mesh, 'indicator-scene');
}
}
});
It could look something like this:
function moveCameraToPointOnSheet(x, y) {
const intersection = viewer2D.hitTest(x, y);
if (intersection) {
const worldPos = sheetToWorld(intersection.intersectPoint, viewer2D.model, viewer3D.model);
if (worldPos) {
const eyeVec = viewer3D.navigation.getEyeVector();
const newPos = worldPos;
const newTarget = newPos.clone().add(eyeVec);
const fov = viewer3D.navigation.getHorizontalFov();
viewer3D.navigation.setRequestTransition(true, newPos, newTarget, fov);
}
}
});

Google Map Lite Mode moveCamera does not call setOnCameraIdleListener

Map shows correctly, then I check that the map is fully loaded before I do the moveCamera on it. The map then shows the correct area as defined by the bounds. But after the move, the setOnCameraIdleListener is never called as is expected. Here is the bit of code of question
map.setOnMapLoadedCallback(GoogleMap.OnMapLoadedCallback {
Log.e(tag, "setOnMapLoadedCallback")
//set camera bounds
map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100))
})
map.setOnCameraIdleListener {
//create snapshot
Log.e(tag, "setOnCameraIdleListener")
}
I am using lite mode for the map and according to the documentation it looks like it should be supported but I couldn't find anything definite.
What may I be missing?
UPDATE:
Here is how I worked around this bug in the SDK.
Created a val defined as the callback.
private val snapshotReadyCallback : GoogleMap.SnapshotReadyCallback = GoogleMap.SnapshotReadyCallback {
SaveSnapshot(it)
}
"it" is a bitmap of the map. You could do the saving directly in the callback but I call a function instead.
Within setOnMapLoadedCallback did the following
gmap?.setOnMapLoadedCallback {
gmap?.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100))
//2 seconds lag to ensure camera has had time to move
//since camera move override doesnt work in setOnMapLoadedCallback
handler.postDelayed({ // Do something after 2s = 2000ms
gmap?.snapshot(snapshotReadyCallback)
}, 2000)
}
Adding the delay to grab the snapshot allowed enough time for the camera to have moved already. It will then call the snapshotReadyCallback which will then call a function that does the actual saving.

How to check if a marker is in a cluster?

With Leaflet.Markercluster, how is it possible to check if a marker is in a cluster?
Use Leaflet's hasLayer() function
Regular visible markers technically exist as layers in the map. Leaflet also has a function hasLayer() that returns true/false whether a given reference, like a stored marker, currently exists (ie "is visible") in the map as a layer.
For my specific problem, I gave a special visual decoration to a selected map marker (e.g. red border), and this decoration remained even after that marker went in-and-out of a cluster. I needed the selected marker to deselect itself if it entered a cluster.
Below is rough logic that allows me to check whether a given marker reference is visible to the user after a cluster event (that may occur for any reason, like zoom events or non-user driven movements in the map).
Relevant abbreviated code:
I hold my clustering like this...
this.markersClustered = L.markerClusterGroup({ // Lots of stuff here... } })
In my click event for individual markers, I store the marker in a "selectedItem" object (which I use for all kinds of other logic in my app)...
onEachFeature(feature, marker) {
marker.on("click", e => {
// ... (lots of code) ...
// Save instance of the marker; I call it "layer" only
// because I only use this for the hasLayer() check
this.selectedItem.layer = marker
// Here do other stuff too, whatever you need...
//this.selectedItem.target = e.target
//this.selectedItem.latlng = e.latlng
//this.selectedItem.id = e.target.feature.id
//this.selectedItem.icon = layer._icon
// ... (lots of code) ...
})
}
When cluster animations end, using hasLayer(), check whether the selected marker is in a cluster, and do stuff.
Note: the check is done at the END of clustering animation in my use case, because I didn't want the user to see the selected marker lose it's special visual decoration while the clustering animation was happening (it would appear buggy).
this.markersClustered.on('animationend', (e) => {
// Check visibility of selected marker
if(this.map.hasLayer(this.selectedItem.layer)) {
// True: Not in a cluster (ie marker is visible on map)
} else {
// False: In a cluster (ie marker is not visible on map)
}
console.log("Selected marker visible?:" + this.map.hasLayer(this.selectedItem.layer))
})

URLImage on MapContainer not displayed on actual device and flickering in simulator

My app features a map, on which the user's avatar is displayed in the center and where markers including photo should be added when the user moves the map.
On the simulator, the markers are added but the images disappear as soon as I release the pointer then only the placeholders remain (this is what I call flickering). On the device, nothing is shown apart from the user's avatar.
As you can see the image does not remain on the map, only the placeholder does. The user icon is southern on the map but it is shown.
Please note: I am not receiving 404 errors and there is only one listener on the map (see below):
Here is how I trigger the map update:
googleMap.addMapListener((source, zoom, center) -> {
showReportsOnMap(googleMap, center, theme, currentForm, selectCategoryButton.getWidth());
});
And here is how I add the reports the map:
public void showReportsOnMap(
MapContainer currentMap,
Coord center,
Resources theme,
Form f,
int reportImageWidth) {
/**
* Get the map borders (CAUTION : it can be NaN)
*/
Coord NE = currentMap.getCoordAtPosition(currentMap.getAbsoluteX() + currentMap.getWidth(), currentMap.getAbsoluteY());
Coord SW = currentMap.getCoordAtPosition(currentMap.getAbsoluteX(), currentMap.getAbsoluteY() + currentMap.getHeight());
boolean bordersKnownAndValid = false;
// Checks that the borders does not contain NaN as longitudes and latitudes
if (!Double.isNaN(NE.getLatitude())
&& !Double.isNaN(NE.getLongitude())
&& !Double.isNaN(SW.getLatitude())
&& !Double.isNaN(SW.getLongitude())) {
// The borders can be used
bordersKnownAndValid = true;
}
if (bordersKnownAndValid) {
ArrayList<Report> localReports = (ArrayList<Report>) (Report.getReportsWithinBoundingBounds(NE, SW, selectedCategoryIdToBeShownOnMap).get(1));
// Revalidate only if we have something new to show
if (localReports.size() > 0) {
currentMap.clearMapLayers();
currentMap.addMarker(ParametresGeneraux.getCurrentUser().getUserIcon(),
new Coord(ParametresGeneraux.getCurrentUser().getCurrentUserLocation().getLatitude(),
ParametresGeneraux.getCurrentUser().getCurrentUserLocation().getLongitude()),
ParametresGeneraux.getCurrentUser().getUserNickname(), "", null);
Image tempPlaceholder = Image.createImage(
reportImageWidth,
reportImageWidth,
ParametresGeneraux.accentColor);
Graphics gr = tempPlaceholder.getGraphics();
gr.setAntiAliased(true);
gr.setColor(ParametresGeneraux.accentColor);
gr.fillArc(0, 0, reportImageWidth, reportImageWidth, 0, 360);
EncodedImage roundPlaceholder = EncodedImage.createFromImage(tempPlaceholder, true);
// Add the report on the map
for (Report report : localReports) {
String photoFilenameInStorage = Report.getFilename(report.getPhotoPath())
+ ParametresGeneraux.SUFFIX_ON_MAP_IMAGE;
EncodedImage reportIcon = EncodedImage.createFromImage(URLImage.createToStorage(roundPlaceholder,
photoFilenameInStorage,
report.getPhotoPath(),
ParametresGeneraux.RESIZE_SCALE_WITH_ROUND_MASK
),
false); // we want transparency png otherwise it shows black edges
currentMap.addMarker(reportIcon,
new Coord(report.getLocation().getLatitude(), report.getLocation().getLongitude()
),
report.getCategory().getName(), "",
(evt) -> {
// Opens the detail form about this report
new ReportDetailsForm(theme, report, f.getClass()).show();
});
}
currentMap.setCameraPosition(new Coord(center.getLatitude(), center.getLongitude()));
currentMap.zoom(new Coord(center.getLatitude(),
center.getLongitude()),
ParametresGeneraux.getUserZoomLevelOnMap());
currentMap.animate();
//f.forceRevalidate();
}
}
}
So I guess that the flickering in the simulator is a kind of slow motion of what happens on the device although the device does not show the placeholder.
What should I do to make the markers appear with an image?
EDIT March 8th 2017
On simulator, if I show a Dialog just before adding the marker to the map with this code :
Dialog.show("Photo", report.getAddress(), Dialog.TYPE_INFO, reportIcon, "OK", null);
The icon is well displayed in the Dialog (see screen capture below)
and then the image appears on the map without flickering any more as depicted below :
However on an actual Android device even the Dialog does not appear.
Finally I don't know why the Dialog makes then the markers behave as expected on the simulator but not on the device, so I am a bit at lost!
Any help would be precious.
The problem is that URLImage may not have finished downloading by the time you added it as a marker. If you call EncodedImage.createFromImage(urlImage) before URLImage has finished downloading, then you'll be creating an encoded image of the urlImage's placeholder.
the com.codename1.io.Util class includes quite a few methods for downloading images from URLs. Some are blocking, and some use a callback. Either way you just need to ensure that the image is actually downloaded before adding it to a map.
NOTE: Normally this wouldn't be an issue with URLImage - e.g. if you were adding it to a Button or a Label. It is only a problem here because the MapContainer is native, and it actually needs to pass the image data to the native layer at the time that setMarker() is called.

MapControl differentiate between user or programmatic center change

In the WinRt/WP 8.1 MapControl, how do I differentiate between when the user changed the center of the screen by swiping vs a programmatic change?
The WinRt/WP 8.1 MapControl has a CenterChanged event ( http://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.maps.mapcontrol.centerchanged.aspx ), but this does not provide any info about what caused the center change.
Is there any other way of knowing whether or not the user changed the map center?
/* To give some more context, my specific scenario is as follows:
Given an app which shows a map, I want to track the gps position of a user.
If a gps position is found, I want to put a dot on the map and center the map to that point.
If a gps position change is found, I want to center the map to that point.
If the user changes the position of the map by touch/swipe, I no longer want to center the map when the gps position changes.
I could hack this by comparing gps position and center, but he gps position latLng is a different type & precision as the Map.Center latLng. I'd prefer a simpler, less hacky solution.
*/
I solved this by setting a bool ignoreNextViewportChanges to true before calling the awaitable TrySetViewAsync and reset it to false after the async action is done.
In the event handler, I immediately break the Routine then ignoreNextViewportChanges still is true.
So in the end, it looks like:
bool ignoreNextViewportChanges;
public void HandleMapCenterChanged() {
Map.CenterChanged += (sender, args) => {
if(ignoreNextViewportChanges)
return;
//if you came here, the user has changed the location
//store this information somewhere and skip SetCenter next time
}
}
public async void SetCenter(BasicGeoposition center) {
ignoreNextViewportChanges = true;
await Map.TrySetViewAsync(new Geopoint(Center));
ignoreNextViewportChanges = false;
}
If you have the case that SetCenter might be called twice in parallel (so that the last call of SetCenter is not yet finished, but SetCenter is called again), you might need to use a counter:
int viewportChangesInProgressCounter;
public void HandleMapCenterChanged() {
Map.CenterChanged += (sender, args) => {
if(viewportChangesInProgressCounter > 0)
return;
//if you came here, the user has changed the location
//store this information somewhere and skip SetCenter next time
}
}
public async void SetCenter(BasicGeoposition center) {
viewportChangesInProgressCounter++;
await Map.TrySetViewAsync(new Geopoint(Center));
viewportChangesInProgressCounter--;
}