Auto Zoom mapView based on the two different co-ordinates - google-maps

I can able to show markers on Google maps when they are near to eachother, but when the distance between is high, I can able to see only one lat&lon.
Here is my code
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng google_api_lat_lon = new LatLng(lat, lon);
float zoomLevel = 16.0f;
Marker markerAPILocation = mMap.addMarker(new MarkerOptions().position(google_api_lat_lon).title(title).icon(BitmapDescriptorFactory.fromResource(R.drawable.saved_locaitons)));
markerAPILocation.showInfoWindow();
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(google_api_lat_lon, zoomLevel));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
// mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMapToolbarEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(false);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(google_api_lat_lon, zoomLevel));
}
I need to show two co-ordinates in the map it can be achieved only by adjusting zoom level based on the distance. I tried above code but its not working for me.

I solved it by simply adding,
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(google_api_lat_lon);
builder.include(current_lat_lon);
LatLngBounds bounds = builder.build();
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));

Related

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);
}

Draw route on Windows Phone 8 map as position changes?

Scenario:
I want a user to see a map and their current position. Then, if they click "start", navigation will begin and they'll see their "route" drawn onto the map as their position changes, similar to how some fitness apps work that map out your run/walk. The goal is to do this in real-time as the user's position changes.
Options:
The way I see it, there are two options: 1) use a RouteQuery and Map.AddRoute from the starting position, to the next position (when the position changes), keeping track of the last position, and always drawing a new MapRoute from that position to the new, or 2) displaying the user's current position as a dot that moves as their position changes, and then maybe when they press "stop", draw a MapRoute for each of their positions in order to show their full route.
I'd really prefer option #1 because the user can see their route progression, etc., as they go.
Here is the code that I'm using:
XAML:
<maps:Map x:Name="MainMap" />
<Button x:Name="btnStart" Content="Start"/>
<Button x:Name="btnStop" Content="Stop" IsEnabled="False"/>
Code-behind:
Global Variables:
GeoCoordinateWatcher watcher;
List<GeoCoordinate> listCoordinates;
GeoCoordinate lastCoordinate;
btnStart.Tap():
private void btnStart_Tap(object sender, GestureEventArgs e)
{
if (watcher == null)
{
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
watcher.MovementThreshold = 20;
watcher.StatusChanged += watcher_StatusChanged;
watcher.PositionChanged += watcher_PositionChanged;
}
watcher.Start();
}
watcher.StatusChanged():
private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Initializing:
btnStart.IsEnabled = false;
btnStop.IsEnabled = true;
break;
case GeoPositionStatus.NoData:
lblStatus.Text = "location data is not available.";
break;
case GeoPositionStatus.Ready:
lblStatus.Text = "location data is available.";
break;
}
}
watcher.PositionChanged():
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (listCoordinates == null)
{
// first time through:
listCoordinates = new List<GeoCoordinate>();
listCoordinates.Add(e.Position.Location);
lastCoordinate = e.Position.Location;
return;
}
else
{
listCoordinates.Add(e.Position.Location);
DrawRoute(e.Position.Location);
lastCoordinate = e.Position.Location;
}
}
DrawRoute function:
private void DrawRoute(GeoCoordinate newPosition)//
{
RouteQuery query = new RouteQuery()
{
TravelMode = TravelMode.Driving,
Waypoints = new List<GeoCoordinate>() { MainMap.Center, newPosition }
};
query.QueryCompleted += RouteQueryCompleted;
query.QueryAsync();
MainMap.Center = newPosition;
lastCoordinate = newPosition;
}
And finally, RouteQueryCompleted():
void RouteQueryCompleted(object sender, QueryCompletedEventArgs<Route> e)
{
mapRoute = new MapRoute(e.Result);
MainMap.AddRoute(mapRoute);
}
What happens:
It appears to work for a second as I begin driving, a short line is drawn where my start position is, but then about 10 second in, a line is randomly drawn down a nearby street (probably equivalent to 3 or 4 blocks long) and then down another block on a side road (while the whole time I haven't even driven ONE block, let alone make any turns!). It's very bizarre and definitely not accurate. I can upload a screenshot to better illustrate it if need be.
Can anyone see what I'm doing wrong in my code or is there a better way to accomplish this? I wasn't sure if this was the best way but I wasn't able to find any examples suggesting otherwise.
I ended up using MapPolyLine to draw a line between the last GeoCoordinate and the new one.
MapPolyline line = new MapPolyline();
line.StrokeColor = Colors.Blue;
line.StrokeThickness = 15;
line.Path.Add(lastCoordinate);
line.Path.Add(pos);
MainMap.MapElements.Add(line);
I am not sure why you are using RouteQuery for your task. Generally, you use this when you want the map sdk to determine a route for you given a set of coordinates. In your case however, you always know where you are through PositionChanged event. It will be easier to plot directly on the map as you move.
Something like this
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e) {
Plot(e.Position.Location);
}
void Plot(GeoCoordinate pos) {
var ellipse = new Ellipse();
ellipse.Fill = new SolidColorBrush(System.Windows.Media.Colors.Blue);
ellipse.Height = 15;
ellipse.Width = 15;
ellipse.Opacity = 25;
var mapOverlay = new MapOverlay();
mapOverlay.Content = ellipse;
mapOverlay.PositionOrigin = new System.Windows.Point(0.5, 0.5);
mapOverlay.GeoCoordinate = pos;
var mapLayer = new MapLayer();
mapLayer.Add(mapOverlay);
MainMap.Layers.Add(mapLayer);
}

Google Map V2 disable MyLocation blue icon

When i setLocationSource, Google Map will display the blue icon automatically. Anyone know how to remove the blue icon??
Thanks.
Something like that
There is my coding:
private Marker myLocation = null;
private void prepareMapSetting(GoogleMap aGoogleMap)
{
aGoogleMap.setLocationSource(mLocationSource);
aGoogleMap.setOnMyLocationChangeListener(mOnMyLocationChangeListener);
aGoogleMap.setOnMapLongClickListener(mOnMapLongClickListener);
aGoogleMap.setMyLocationEnabled(true);
}
private OnMapLongClickListener mOnMapLongClickListener = new OnMapLongClickListener()
{
#Override
public void onMapLongClick(LatLng point)
{
if(null != mOnLocationChangedListener){
if(null == myLocation){
myLocation = getMap().addMarker(new MarkerOptions()
.position(point)
.title("You")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}
else{
myLocation.setPosition(point);
}
Location location = new Location("LongPressLocationProvider");
location.setLatitude(point.latitude);
location.setLongitude(point.longitude);
mOnLocationChangedListener.onLocationChanged(location);
}
}
};
I'm not sure to understand your question (I don't see your image too).
In fact setLocationSource is just to set the location source of the mylocation layer (i.e., the blue dot...)
if you don't want the blue dot, just put
aGoogleMap.setMyLocationEnabled(false);
and don't use the locationSource