google map in codename one - android

i am using code-name one to develop an app which has google map in it, i want when i open the app it gets my current location how could i do that, here is the code i have.
static Location lastKnownLocation;
#Override
protected void beforeMap(Form f) {
MapContainer mapContainer = new MapContainer(new GoogleMapsProvider("AIzaSyCyy_vOWn3DvR3Y8pzAWUmKTzBaDa81Tfc"));
lastKnownLocation = LocationManager.getLocationManager().getLastKnownLocation();
Style s = new Style();
s.setBgTransparency(0);
s.setFgColor(0);
mapContainer.addMarker(FontImage.createMaterial(FontImage.MATERIAL_MY_LOCATION, s).toEncodedImage(), new Coord(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()), "", "", evt -> {
ToastBar.showErrorMessage(lastKnownLocation.toString());
});
mapContainer.addTapListener(evt -> {
Coord coord = mapContainer.getCoordAtPosition(evt.getX(), evt.getY());
mapContainer.addMarker(FontImage.createMaterial(FontImage.MATERIAL_LOCATION_ON, s).toEncodedImage(), coord, "", "", null);
});
f.add(BorderLayout.CENTER, mapContainer);
FloatingActionButton fab = FloatingActionButton.createFAB(FontImage.MATERIAL_ADD);
fab.addActionListener(e -> {
ParseObject object = ParseObject.create("Geo");
object.put("current", new ParseGeoPoint(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()));
if (ParseUser.getCurrent() != null)
object.put("user", ParseUser.getCurrent());
try {
object.save();
ToastBar.showErrorMessage("Geo Sent");
} catch (ParseException ex) {
ex.printStackTrace();
ToastBar.showErrorMessage(ex.getMessage());
}
});
fab.bindFabToContainer(f.getContentPane());
}
}

Notice that on the device your current location will be used and highlighted since the device runs the native maps whereas the simulator runs a simulation.
Having said that you can get your location from the LocationManager class.
E.g.:
Location position = LocationManager.getLocationManager().getCurrentLocationSync();

Related

Update direction path on Google Maps in driving mode

I am using Google Map, now I am showing a polyline b/w my current location to my destination by using Google Direction API with moving marker animation.
Now if I change my path while driving then how can I update that path from my current location to the destination.
Here is my code
#Override
public void onDirectionSuccess(Direction direction, String rawBody) {
if (direction.isOK()) {
route = direction.getRouteList().get(0);
ArrayList<LatLng> directionPositionList = route.getLegList().get(0).getDirectionPoint();
mMap.addPolyline(DirectionConverter.createPolyline(this, directionPositionList, 8, Color.BLUE));
} else {
Toast.makeText(DriversActivity.this, direction.getStatus(), Toast.LENGTH_SHORT).show();
}
Here in OnDirectionSuccess method, m getting the direction. I don't want to call it again and again because the previous line is also there with a new one.
Is anyone can help me out???
please first add this function to activity
private void route(AbstractRouting.TravelMode travelMode, final LatLng end) {
this.end = end;
DataShahrManager dataShahrManager = DataShahrManager.getInstance(activity);
if (dataShahrManager.getMyLocation() != null) {
start = new LatLng(dataShahrManager.getMyLocation().getLatitude(),
dataShahrManager.getMyLocation().getLongitude());
if (end != null) {
mapsFragment.getProgressBar().setVisibility(View.VISIBLE);
Routing routing = new Routing.Builder()
.travelMode(travelMode)
.withListener(this)
.alternativeRoutes(false)
.waypoints(start, end)
.language("fa")
.key("your key")
.build();
routing.execute();
}
} else {
mapsFragment.getLocationProgressBar().setVisibility(View.VISIBLE);
mapsFragment.startLocationFinding();
mapsFragment.setUpMyLocationUsingMap();
if (activity != null) {
Toast.makeText(activity, R.string.finding_your_location, Toast.LENGTH_SHORT).show();
}
mapsFragment.setOnLocationFoundListener(() -> route(AbstractRouting.TravelMode.DRIVING, end));
}
}
so add this line to button
route(AbstractRouting.TravelMode.DRIVING, businessEntity.getLatLng());

In Xamarin.Android is there a simple way to find a map location based on a search-term instead of LatLng?

In iOS maps there is a clear illustration in the guides on how to search the map using a search term:
public void Search (string forSearchString)
{
// create search request
var searchRequest = new MKLocalSearchRequest ();
searchRequest.NaturalLanguageQuery = forSearchString;
searchRequest.Region = new MKCoordinateRegion (map.UserLocation.Coordinate, new MKCoordinateSpan (0.25, 0.25));
// perform search
var localSearch = new MKLocalSearch (searchRequest);
localSearch.Start (delegate (MKLocalSearchResponse response, NSError error) {
if (response != null && error == null) {
this.MapItems = response.MapItems.ToList ();
this.TableView.ReloadData ();
} else {
Console.WriteLine ("local search error: {0}", error);
}
});
}
However every android example I've seen is instead using coordinates.
Is there a simple equivalent for using a search-term for Android?
Thanks
You can use Google's Places API.
Note: You are using a lat/long in your example to define the the search region.
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.AddApi(PlacesClass.GEO_DATA_API)
.AddApi(PlacesClass.PLACE_DETECTION_API)
.AddApi(LocationServices.API)
.EnableAutoManage(this, this)
.Build();
mGoogleApiClient.BlockingConnect();
var searchText = "Starbucks Coffee";
var latLngBuilder = LatLngBounds.InvokeBuilder();
var currentLocation = new LatLng(47.60357, -122.3295); // use Seattle, WA as default if Fused location returns null
var mLastLocation = LocationServices.FusedLocationApi.GetLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
currentLocation.Latitude = mLastLocation.Latitude;
currentLocation.Longitude = mLastLocation.Longitude;
}
var zoomFactor = 0.005f; // ~ a few city block... adjust as needed...
latLngBuilder.Include(new LatLng(currentLocation.Latitude - zoomFactor, currentLocation.Longitude - zoomFactor));
latLngBuilder.Include(new LatLng(currentLocation.Latitude + zoomFactor, currentLocation.Longitude + zoomFactor));
var latLngBounds = latLngBuilder.Build();
var results = await PlacesClass.GeoDataApi.GetAutocompletePredictionsAsync(mGoogleApiClient, searchText, latLngBounds, null);
if (results.Status.IsSuccess)
{
Log.Debug("SO", $"{results.Count} {searchText} results were found close to your location");
foreach (var item in results)
{
Log.Debug("SO", $"{item.PlaceId}");
}
}
else
Log.Error("SO", results.Status.StatusMessage);
You can use the Foursquare API to search a place by its name. The API will give you the coordinates.
https://developer.foursquare.com/
In Android you can give coordinates and get the adres list, but if you want the reverse method you should use an API that supports this like Foursquare's.

How to get sample route arcgis in android?

I want to get route between two locations,for that i have found esri sample service i.e :http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World.
But if i use this service i am getting error as Unauthorized access to a secure.
I am unable to use this service,Please tell me if any free service for getting route on arcgis map
Thanks.
my code:
public void getRouteFromSource(Geometry current_location,Geometry destination_point,boolean isCurrentLocation){
routeLayer = new GraphicsLayer();
mMapView.addLayer(routeLayer);
// Initialize the RouteTask
try {
String routeTaskURL = "http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World";
mRouteTask = RouteTask.createOnlineRouteTask(routeTaskURL, null);
} catch (Exception e1) {
e1.printStackTrace();
}
// Add the hidden segments layer (for highlighting route segments)
hiddenSegmentsLayer = new GraphicsLayer();
mMapView.addLayer(hiddenSegmentsLayer);
QueryDirections(current_location, destination_point,isCurrentLocation);
}
private void QueryDirections(final Geometry sourceGeometry, final Geometry destinationGeometry,boolean isCurrentLocation) {
// Show that the route is calculating
if(isCurrentLocation==false){
dialog = ProgressDialog.show(mContext, PollingStationLocatorContant.plase_wait,
"Calculating route...", true);
}
// Log.e("mLocation", "mLocation "+sourceGeometry);
// Log.e("POINTTT", "POINTTT"+p);
// Spawn the request off in a new thread to keep UI responsive
Thread t = new Thread() {
private RouteResult mResults;
#Override
public void run() {
try {
// Start building up routing parameters
/*Point startPoint = new Point(78.4867, 17.3850);
Point stopPoint = new Point(79.5941, 17.9689);*/
// Log.e("mLocation.getX()",""+ p.getX()+"---"+ p.getY());
// Log.e("mLocation.getY()",""+ mLocation.getX() +"----"+ mLocation.getY());
//Point startPoint = new Point(mLocation.getX(), mLocation.getY());
//Point stopPoint = new Point(p.getX(), p.getY());
StopGraphic point1 = new StopGraphic(sourceGeometry);
StopGraphic point2 = new StopGraphic(destinationGeometry);
Log.e("point1", ""+point1);
Log.e("point2", ""+point2);
NAFeaturesAsFeature rfaf = new NAFeaturesAsFeature();
// Convert point to EGS (decimal degrees)
// Create the stop points (start at our location, go
// to pressed location)
rfaf.setFeatures(new Graphic[] { point1, point2 });
rfaf.setCompressedRequest(true);
// RouteParameters r = new RouteParameters();
RouteParameters rp = mRouteTask.retrieveDefaultRouteTaskParameters();
//rp.setImpedanceAttributeName("Length");
rp.setReturnDirections(false);
// Assign the first cost attribute as the impedance
rp.setStops(rfaf);
// Set the routing service output SR to our map
// service's SR
rp.setOutSpatialReference(mMapView.getSpatialReference());
//rp.setImpedanceAttributeName("");
// Solve the route and use the results to update UI
// when received
mResults = mRouteTask.solve(rp);
List<Route> routes = mResults.getRoutes();
Route mRoute = routes.get(0);
Geometry routeGeom = mRoute.getRouteGraphic().getGeometry();
Graphic symbolGraphic = new Graphic(routeGeom, new SimpleLineSymbol(Color.BLUE,5));
//SimpleMarkerSymbol sls = new SimpleMarkerSymbol(Color.RED, 10,STYLE.CIRCLE);
PictureMarkerSymbol pls=new PictureMarkerSymbol(mContext.getResources().getDrawable(R.drawable.animation_image));
mMapView.setExtent(routeGeom, 20);
Graphic destinatonGraphic = new Graphic(sourceGeometry, pls);
mGraphicsLayer.addGraphic(symbolGraphic);
mDestinationGraphicLayer.addGraphic(destinatonGraphic);
mMapView.addLayer(mGraphicsLayer);
mMapView.addLayer(mDestinationGraphicLayer);
mHandler.post(mUpdateResults);
} catch (Exception e) {
mDestinationGraphicLayer.removeAll();
noRouteFound=true;
e.printStackTrace();
mHandler.post(mUpdateResults);
}
}
};
// Start the operation
t.start();
}
void updateUI() {
if(dialog!=null && dialog.isShowing()){
dialog.dismiss();
if(noRouteFound){
Toast.makeText(mContext, "Unable to find route.Please select with in State", Toast.LENGTH_LONG).show();
}
}
}
Disregarding geocoding services (which may be called for free if data is not stored) routing services do require a token.
As stated in the documentation:
Required parameters: token
Use this parameter to specify a token that provides the identity of a
user that has the permissions to access the service. Accessing
services provided by Esri provides more information on how such an
access token can be obtained.
What you can do is to go here and register a free developer account. You will receive a free token and its related amount of free credits that you can use to query the routing API.
However, the documentation linked above shows samples of response for all possible situations (error, route ok, route not found).
After creating a free developer account follow these steps.
Inside your getRouteFromSource function replace the existing code with this.
TOKEN = "The token you receive after you sign up";
CLIENT_ID = "The client_id you receive after you sign up";
try {
UserCredentials authenticate= new UserCredentials();
authenticate.setUserAccount("your username", "your password");
authenticate.setUserToken(TOKEN, CLIENT_ID);
mRouteTask = RouteTask
.createOnlineRouteTask(
"http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",
authenticate);
} catch (Exception e1) {
e1.printStackTrace();
}
This should solve your problem.

Choose from map with android marshmallow

Now I'm using android map clicklistener to allow user to choose location from map. When the click the map the chosen location latitude and longitude are printed correctly in the toast, then I send this data to another fragment through bundle.
On android marshmallow devices it always transferred with null value, even it's working properly with all other versions.
I don't know what is the problem, so I'll be blessed for any help
Here is my code
try {
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate Update = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(Update);
final Marker TP = map.addMarker(new MarkerOptions().position(latLng).title(""));
TP.setDraggable(true);
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
Toast.makeText(getActivity(), point.toString(), Toast.LENGTH_SHORT).show();
String latMap = String.valueOf(point.latitude);
String lngMap = String.valueOf(point.longitude);
((MainActivity)getActivity()).aqarLat = String.valueOf(point.latitude);;
((MainActivity)getActivity()).aqarLong = String.valueOf(point.longitude);
myBundle = new Bundle();
myBundle.putString("latMap" , latMap);
myBundle.putString("lngMap" , lngMap);
sharedPreferences.edit().putString("latMap", String.valueOf(point.latitude)).commit();
sharedPreferences.edit().putString("longMap", String.valueOf(point.longitude)).commit();
TP.setPosition(point);
}
});
} catch (Exception e) {
e.printStackTrace();
}
Thanks in advance

Android get lat&long from google address

I have implemented Google Place API autocomplete functionality for my application like this: https://developers.google.com/places/training/autocomplete-android
No it just makes a Toast with that address.
How can I get the latitude and longitude from the selected address?
Use the method
public List<Address> getFromLocationName (String locationName, int maxResults) from Android Geocoder API, pass in the location name and the maximum number of results you would like and you should be good to go.
Eg.
Geocoder coder = new Geocoder(this);
try {
ArrayList<Address> adresses = (ArrayList<Address>) coder.getFromLocationName("Some Address", 10);
for(Address add : adresses){
double longitude = add.getLongitude();
double latitude = add.getLatitude();
}
} catch (IOException e) {
e.printStackTrace();
} catch(IllegalArgumentException e){
e.printStackTrace();
}
If it helps, I've recently created a library in Java for Google Places API.
Autocompletion is as simple as:
GooglePlaces client = new GooglePlace("apiKey");
List<Prediction> predictions = client.getPlacePredictions("Empire");
for (Prediction prediction : predictions) {
String description = prediction.getDescription();
// etc etc
}
And getting a latitude-longitude from an address is as simple as.
List<Place> places = client.getPlacesByQuery(address, GooglePlaces.MAXIMUM_RESULTS);
for (Place place : places) {
if (place.getAddress().equals(address)) {
double lat = place.getLatitude();
double lng = place.getLongitude();
}
}
https://github.com/windy1/google-places-api-java
You can simply use google maps api to get the lat and long
http://maps.google.com/maps/api/geocode/json?address=&sensor=false
In the above link u have to add the address next to "address=" and u can get the json data with lat and long and some other infos.
Try GeoDataClient. Refer GeoDataClient and Place IDs and details.
geoDataClient.getPlaceById(autoCompletePredictionItem.getPlaceId())
.addOnCompleteListener(new OnCompleteListener<PlaceBufferResponse>() {
#Override
public void onComplete(#NonNull Task<PlaceBufferResponse> task) {
if (task.isSuccessful()) {
PlaceBufferResponse places = task.getResult();
Place myPlace = places.get(0);
Log.e(TAG, "Place found: " + myPlace.getLatLng().toString());
places.release();
} else {
Log.e(TAG, "Place not found.");
}
}
});
According to updated documents, GeoDAtaClient is deprecated. New way is to use this:
// Define a Place ID. val placeId = "INSERT_PLACE_ID_HERE"
// Specify the fields to return. val placeFields = listOf(Place.Field.ID, Place.Field.NAME)
// Construct a request object, passing the place ID and fields array. val request = FetchPlaceRequest.newInstance(placeId, placeFields)
placesClient.fetchPlace(request)
.addOnSuccessListener { response: FetchPlaceResponse ->
val place = response.place
Log.i(PlaceDetailsActivity.TAG, "Place found: ${place.name}")
}.addOnFailureListener { exception: Exception ->
if (exception is ApiException) {
Log.e(TAG, "Place not found: ${exception.message}")
val statusCode = exception.statusCode
TODO("Handle error with given status code")
}
}
https://developers.google.com/maps/documentation/places/android-sdk/place-details#maps_places_get_place_by_id-kotlin

Categories

Resources