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.
Related
var _locator = CrossGeolocator.Current;
var mapPosition = await _locator.GetPositionAsync();
var mapSpan = MapSpan.FromCenterAndRadius(
new Xamarin.Forms.Maps.Position(mapPosition.Latitude, mapPosition.Longitude),
Distance.FromMiles(2)
);
Map.MoveToRegion(mapSpan);
Using Xamarin.Forms.Maps.Postion() the correct lat and lon coordinates are calculated.
However, when I add it to MapSpan, the coordinates change to somewhere in the middle of the Atlantic ocean. Not sure what is causing this?
UPDATE:
So the problem is definitely in the Android project. For some reason, GoogleMaps is not recognizing the location passed by the Map Renderer in the shared project. OnMapReady is just using the default lat/lon.
SUCCESS!!!
async Task<Plugin.Geolocator.Abstractions.Position> GetPositionAsync()
{
var _locator = CrossGeolocator.Current;
Plugin.Geolocator.Abstractions.Position myPosition = await _locator.GetPositionAsync();
return myPosition;
}
public void OnMapReady(GoogleMap googleMap)
{
Plugin.Geolocator.Abstractions.Position myPosition = Task.Run(GetPositionAsync).Result;
map = googleMap;
map.MoveCamera(
CameraUpdateFactory.NewLatLng(
new LatLng(myPosition.Latitude, myPosition.Longitude)));
map.AnimateCamera(
CameraUpdateFactory.ZoomTo(10));
The MapSpan properties LatitudeDegree and LongitudeDegrees refer to the degrees of latitude and longitude that are spanned (i.e. the number of degrees of the map that are shown within its view.)
If you are looking for the lat/lng of the center of the map in your span, refer to the Center properties which is a Maps.Postion object.
Re: https://developer.xamarin.com/api/type/Xamarin.Forms.Maps.MapSpan/
Example:
var mapPosition = new Position(38.29, -77.45);
var mapSpan = MapSpan.FromCenterAndRadius(mapPosition, Distance.FromMiles(2));
map.MoveToRegion(mapSpan);
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.
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());
// ...
}
// ...
}
Not sure what is going on here, but I want it to make an additional circle every second as the device moves. All it does is make 1 circle. I want the circles to highlight the route I have taken. Recommendations? Thanks
LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
Location location = locationmanager.getLastKnownLocation(provider);
locationmanager.requestLocationUpdates(provider, 1000, 0, (LocationListener) this);
CircleOptions circleOptions = new CircleOptions()
.center(new LatLng(location.getLatitude(), location.getLongitude()));
circleOptions.radius(3.048); // In meters
mMap.addCircle(circleOptions);
Put:
CircleOptions circleOptions = new CircleOptions()
.center(new LatLng(location.getLatitude(), location.getLongitude()));
circleOptions.radius(3.048); // In meters
mMap.addCircle(circleOptions);
inside onLocationChanged(Location location) callback.
How i can add multiple push pins to bing map control. In my application, i tried to add some user control(Push pins) as children of that map control. But the issue is that when i performing zoom -in and zoom-out operation the push pin moves around the map and miss places the position.
Here is the code i used for adding multiple push pins to the map :
foreach (var item in PushPinCollection)
{
var pin = new CustomMapPin(Convert.ToInt32(item.BackgroundColorID)) { Name = item.ID.ToString() };
pin.DoubleTapped += PushpinTapped1;
pin.Tapped += PinTapped;
var loc = new Location(Convert.ToDouble(item.Latitude, System.Globalization.CultureInfo.InvariantCulture), Convert.ToDouble(item.Longitude, System.Globalization.CultureInfo.InvariantCulture));
pin.SetValue(MapLayer.PositionProperty, loc);
NoteMap.Children.Add(pin);
}
Try this:
Bing.Maps.Location loc = new Bing.Maps.Location
{
Latitude = latitude,
Longitude = longitude
};
myMap.SetView(loc, 13);
Pushpin pushpin = new Pushpin();
pushpin.Tapped +=pushpin_Tapped;
pushpin.Text = address;
MapLayer.SetPosition(pushpin, loc);
myMap.Children.Add(pushpin);