Get marker position before dragging primefaces - google-maps

I want to store the previous location before dragging a marker using PrimeFaces GMap - Draggable Markers
How to do it ?
showcase : GMap - Draggable Markers :
http://www.primefaces.org/showcase/ui/gmapDraggableMarkers.jsf

You could store copies of the original Marker objects and then, in the onMarkerDrag handler, you could find the original Marker that corresponds to the one passed by the MarkerDragEvent.
I say "copies" because it is possible that Primefaces modifies the LatLng of original Marker instead of creating a new one (most likely). You can use the "data" or "title" attributes to give them IDs and correctly match the copied Markers.
I can probably explain this with code, let me know if you need help.
Edit:
To meet your requirement, I would adapt the Primefaces showcase example as follows (notice that it requires the Marker's title to be unique. If this is not possible, implement this using the data attribute of the Marker class.):
package org.primefaces.examples.view;
//...
public class MapBean implements Serializable {
private MapModel draggableModel;
private Map<String, LatLng> positions = new HashMap<String, LatLng>(); // new
public MapBean() {
draggableModel = new DefaultMapModel();
positions.put("Konyaalti", new LatLng(36.879466, 30.667648));
positions.put("Ataturk Parki", new LatLng(36.883707, 30.689216));
positions.put("Karaalioglu Parki", new LatLng(36.879703, 30.706707));
positions.put("Kaleici", new LatLng(36.885233, 30.702323));
for (Map.Entry<String, LatLng> e : positions.entrySet()) {
Marker m = new Marker(e.getValue(), e.getKey());
m.setDraggable(true);
draggableModel.addOverlay(m);
}
}
public void onMarkerDrag(MarkerDragEvent event) {
marker = event.getMarker();
addMessage(new FacesMessage(FacesMessage.SEVERITY_INFO, "Marker Dragged", "Lat:" + marker.getLatlng().getLat() + ", Lng:" + marker.getLatlng().getLng()));
// update position and get the old one
LatLng oldPosition = positions.put(marker.getTitle(), marker.getLatlng());
// ...
}
// ...
}

Related

Xamarin Android Google Map - Add marker where user clicks

In Xamarin Forms, I am using a custom renderer in Android for a map I have implemented using Android.Gms.Maps I want to write functionality that adds a marker in the area a user clicked on the map.
public async void OnMapReady(GoogleMap googleMap)
{
map.MapClick+= HandleMapClick;
}
In my HandleMapClick() function, how do I use the addMarker() function to add a marker to the area which a user clicked on the map?
The GoogleMap.MapClickEventArgs contains a "Point" that contains the lat/long of the user' click. Create a MarkerOption, assign it that point and add it to your map.
googleMap.MapClick += (object sender, GoogleMap.MapClickEventArgs e) =>
{
using (var markerOption = new MarkerOptions())
{
markerOption.SetPosition(e.Point);
markerOption.SetTitle("StackOverflow");
// save the "marker" variable returned if you need move, delete, update it, etc...
var marker = googleMap.AddMarker(markerOption);
}
};

How to show the path and distance on Google Map - Xamarin

I have a page(fragment) that shows google maps together with 1 marker icon. So now i would like to pass source and destination coordinates to this map so that it can show the shortest route together with the distance in Km. E.g i want the map to show the blue path in the image below :
Here is my code :
private void SetUpMap()
{
if (GMap == null)
{
ChildFragmentManager.FindFragmentById<MapFragment>(Resource.Id.googlemap).GetMapAsync(this);
}
}
public void OnMapReady(GoogleMap googleMap)
{
this.GMap = googleMap;
GMap.UiSettings.ZoomControlsEnabled = true;
LatLng latlng = new LatLng(Convert.ToDouble(gpsLatitude), Convert.ToDouble(gpsLongitude));
CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latlng, 15);
GMap.MoveCamera(camera);
MarkerOptions options = new MarkerOptions()
.SetPosition(latlng)
.SetTitle("Chennai");
GMap.AddMarker(options);
}
I got my answer from this post :
Adding polyline between two locations google maps api v2
I converted the java code to C# and it worked fine.

Drawing path between two markers Google Maps V2

I have two markers, namely startLocation and the other is stopLocation. startLocation will detect the user's current location, and then the user will walk, and when they stop they'll press stop and stopLocation will be captured as their new current location. I want to draw a polyline as the user is moving from the startLocation to stopLocation.
Alternatively, the polyline can also be drawn after both markers for start and stop location has been created - whichever is more implementable.
How can this be done? Most of the answers refer to retrieving routes and then drawing the polylines, but that's not what I want - I want to get the user's personalized route. In short, I want to record the route the user has taken. I've managed to create both markers already:
btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Create Start Marker
// get current location
LocationManager locManager;
String context = Context.LOCATION_SERVICE;
locManager = (LocationManager) getSystemService(context);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_FINE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_LOW);
String provider = locManager.getBestProvider(c, true);
Location loc = locManager.getLastKnownLocation(provider);
LatLng currentPosition = updateWithNewLocation(loc);
Marker startLocation = map.addMarker(new MarkerOptions()
.position(currentPosition)
.title("Start Location")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 17));
}
});
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Create Stop
// get current location
LocationManager locManager;
String context = Context.LOCATION_SERVICE;
locManager = (LocationManager) getSystemService(context);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_FINE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_LOW);
String provider = locManager.getBestProvider(c, true);
Location loc = locManager.getLastKnownLocation(provider);
LatLng currentPosition = updateWithNewLocation(loc);
Marker stopLocation = map.addMarker(new MarkerOptions()
.position(currentPosition)
.title("Stop Location")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 17));
// Draw dynamic line
}
});
Now all I need is to draw the line between the two markers. Thanks!
There is no way to do this without tracking the user's location. You should use the requestLocationUpdates function to listen and get the update of your user's location. Refer to the developer guide for more information on listening to the GPS location.
String locationProvider = LocationManager.NETWORK_PROVIDER;
// Or, use GPS location data:
// String locationProvider = LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
You might also want to use the snap to road function in the newly released Google Maps Road API, to fix your raw lat/lng from GPS, and get a smoother path on the road. It does not currently have Android APIs, so you might need to use the Web API to access the snap to road service.
https://roads.googleapis.com/v1/snapToRoads?path=-35.27801,149.12958|-35.28032,149.12907|-35.28099,149.12929|-35.28144,149.12984|-35.28194,149.13003|-35.28282,149.12956|-35.28302,149.12881|-35.28473,149.12836
&interpolate=true
&key=API_KEY
After users stopped tracking or reached the end point, you can create a polyline based on their path.
// Instantiates a new Polyline object and adds points to define a rectangle
PolylineOptions rectOptions = new PolylineOptions()
.add(new LatLng(37.35, -122.0))
.add(new LatLng(37.45, -122.0)) // North of the previous point, but at the same longitude
.add(new LatLng(37.45, -122.2)) // Same latitude, and 30km to the west
.add(new LatLng(37.35, -122.2)) // Same longitude, and 16km to the south
.add(new LatLng(37.35, -122.0)); // Closes the polyline.
// Get back the mutable Polyline
Polyline polyline = myMap.addPolyline(rectOptions);
Let me know if it is not clear, and hope it helps.

Why can't this code produce a points layer in GeoTools

I am testing adding a collection of points to a map utilizing the Geotools API. I've been following this example as best I could Problem creating a point and adding it to FeatureCollection, as the example code is old, and things like FeatureCollections is deprecated. I tried using DefaultFeatureCollection instance instead, and I am not sure if I am using it correctly, and that is why the points do not appear on the map. What am I doing wrong? Here is some of my code:
private void plotMarkers() {
final SimpleFeatureType TYPE = this.createFeatureType();
final SimpleFeatureBuilder BLDR = new SimpleFeatureBuilder(TYPE);
DefaultFeatureCollection features = new DefaultFeatureCollection();
// arbitrary start position
Coordinate pos = new Coordinate(0, 0);
final double pointSpacing = 1.0;
String title = "Test";
features.add(creatureFeature(BLDR, pos, title));
// display points on screen
Style style = SLD.createPointStyle("circle", Color.RED, Color.RED, 1.0f, 5.0f);
Layer layer = new FeatureLayer(features, style);
this.getMapContent().addLayer(layer);
}
Maybe this can help you to make it work
private MapContent map;
private static Style pointStyle = SLD.createPointStyle("Circle", Color.RED, Color.RED, 0.5f, POINT_SIZE);
public static void CreatePoints(double X, double Y){
createPointLayer();
createFeatures(X,Y);
}
static void createFeatures(double X, double Y) {
Point point = geometryFactory.createPoint(new Coordinate(X, Y));
pointCollection.add(SimpleFeatureBuilder.build(pointType, new Object[]{point}, null));
//create map layer event
MapLayerEvent mple = new MapLayerEvent(pointLayer, MapLayerEvent.DATA_CHANGED);
//create maplayer list event
MapLayerListEvent mplle = new MapLayerListEvent(map, pointLayer, map.layers().indexOf(pointLayer), mple);
okvir.mapPane.layerChanged(mplle);
System.out.println(MessageFormat.format("Created Point: {0}", point));
}
private static void createPointLayer() {
if (pointType == null) {
pointFeatureTypeBuilder.setName("PointCreated");
pointFeatureTypeBuilder.setCRS(map.getCoordinateReferenceSystem());
pointFeatureTypeBuilder.add("the_geom", Point.class);
pointType = pointFeatureTypeBuilder.buildFeatureType();
pointCollection = new DefaultFeatureCollection(null, pointType);
}
pointLayer = new FeatureLayer(pointCollection, pointStyle);
map.addLayer(pointLayer);
}

PrimeFaces GMap - Drawing multiple polygons

I have a very simple question.
Is there a way to add multiple polygons to PrimeFaces GMap?
If yes, can someone share a snippet/example?
If no, are there any alternatives to GMap in JSF?
Any help will be appreciated! Thanks
The first sentence in the link you provided gives you the answer:
Any number of polygons can be displayed on map.
I would do it the following way:
#ManagedBean
public class PolygonsView implements Serializable {
private MapModel polygonModel;
#PostConstruct
public void init() {
polygonModel = new DefaultMapModel();
//Shared coordinates
LatLng coord1 = new LatLng(36.879466, 30.667648);
LatLng coord2 = new LatLng(36.883707, 30.689216);
LatLng coord3 = new LatLng(36.879703, 30.706707);
//Polygon
Polygon polygon = new Polygon();
polygon.getPaths().add(coord1);
polygon.getPaths().add(coord2);
polygon.getPaths().add(coord3);
polygon.setStrokeColor("#FF9900");
polygon.setFillColor("#FF9900");
polygon.setStrokeOpacity(0.7);
polygon.setFillOpacity(0.7);
polygonModel.addOverlay(polygon);
//here it should be possible to add additional overlays
}
public MapModel getPolygonModel() {
return polygonModel;
}
}
The source code is also from the link you provided. Just create more Polygons and add them as overlay to your MapModel.