cmap.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{ System.out.println("Cmap initial:=lat:-"+lat+" lang:-"+lon);
Toast t=Toast.makeText(getBaseContext(),"Location"+lat+"lang:-"+lon,Toast.LENGTH_LONG);
t.show();
tlname=elname.getText().toString();
tladdr=eladdr.getText().toString();
addressInput=tlname+" "+tladdr;
System.out.println("address:-"+addressInput);
Toast t3=Toast.makeText(getBaseContext(),"Address"+addressInput,Toast.LENGTH_LONG);
t3.show();
try
{
Geocoder gc1 = new Geocoder(
getBaseContext(), Locale.getDefault());
foundAdresses = gc1.getFromLocationName(addressInput, 5);
showAdressResults.sendEmptyMessage(0);
Toast t1=Toast.makeText(getBaseContext(),"Location...."+foundAdresses,Toast.LENGTH_LONG);
t1.show();
System.out.println("faddress:-"+foundAdresses);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (foundAdresses.size() == 0)
{ // if no address found,
// display an error
Dialog locationError = new AlertDialog.Builder(
Gotask.this).setIcon(0).setTitle(
"Error").setPositiveButton(R.string.ok, null)
.setMessage(
"Sorry, your address doesn't exist.")
.create();
locationError.show();
} else
{ // else display address on map
for (int i = 0; i < foundAdresses.size(); ++i)
{
Address x = foundAdresses.get(i);
lat = (x.getLatitude() *100);
lon = (float) x.getLongitude();
System.out.println("Cmap:=lat:-"+lat+" lang:-"+lon);
}
navigateToLocation((lat * 1000000), (lon * 1000000),myMap);
}
}
});
I have also faced this kind of issue in reverse Geo coding so i am use Google api for it.
Refer this link for google api to use in reverse geocoding.
I faced the same problem when i was developing an app based on google maps.The problem was with the devcie ,the one which i am using did't support backend service(a kind of service comes with device) which is responsible for working of GeoCoding related APIs.So i decided to use services exposed by google to query for lat & longitude for the required Address.So just give a try.
Refer this link to know more
http://code.google.com/apis/maps/documentation/geocoding/
Please refer following links:
How can you tell when an Android device has a Geocoder backend service?
Android; Geocoder, why do I get "the service is not available"?
Here is a sample request for geocoding request to obtain Latitude and longitude from response after parsing Xml output.
http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false
There is a clear cut example in the link mentioned earlier.
Related
I am integrating place picker but I have already enable places api but it opens and close immediately.
I have created api key and puted it on manifest file
still it not working.in my logcat it gives me error
2019-03-08 10:31:41.640 2837-2358/? E/Places: Places API for Android does not seem to be enabled for your app. See https://developers.google.com/places/android/signup for more details.
2019-03-08 10:31:41.651 4713-4713/? E/Places: Place Picker closing due to PLACES_API_ACCESS_NOT_CONFIGURED
2019-03-08 10:31:41.775 2837-2358/? E/Places: Places API for Android does not seem to be enabled for your app. See https://developers.google.com/places/android/signup for more details.
2019-03-08 10:31:41.776 2837-2358/? E/AsyncOperation: serviceID=65, operation=SearchPlaces
OperationException[Status{statusCode=PLACES_API_ACCESS_NOT_CONFIGURED, resolution=null}]
here is my code
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="key" />
#SuppressLint("MissingPermission")
private void showPlacePicker() {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(NewOrderActivity.this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, NewOrderActivity.this);
edt_pickup_address.setText(place.getAddress());
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
/* post_area = listAddresses.get(0).getSubLocality();
post_city = listAddresses.get(0).getSubAdminArea();
post_state = listAddresses.get(0).getAdminArea();*/
}
} catch (IOException e) {
e.printStackTrace();
}
String place_phone_number = "" + place.getPhoneNumber();
if (!TextUtils.isEmpty(place_phone_number)) {
String[] phone_number = place_phone_number.split(" ");
String s = "";
for (int i = 0; i < phone_number.length; i++) {
if (i != 0) {
s = s + phone_number[i];
}
}
// et_contact_no_add_company.setText(s);
} else {
// et_contact_no_add_company.setText("");
}
if (place.getWebsiteUri() != null) {
// et_website_add_company.setText("" + place.getWebsiteUri());
} else {
// et_website_add_company.setText("");
}
}
}
}
As per Google new update the Place Picker Deprecate and it will not longer available in future, here is official statement
Deprecation notice: Place Picker
Notice: The Place Picker (Android, iOS) is deprecated as of January 29, 2019. This feature will be turned off on July 29, 2019,
and will no longer be available after that date. To continue using the
Place Picker with Places SDK for iOS v.2.7.0 through the deprecation
period, do NOT disable the Places SDK for iOS. Read the migration
guides (Android, iOS) to learn more.
So, the other side u can use the Place Autocomplete
But here is some limitation in new Place API you must enable the Billing account to use the Place Autocomplete.
Reminder: To use the Places API, you must get an API key and you must
enable billing. You can enable billing when you get your API key (see
the Quick guide) or as a separate process (see Usage and Billing).
Alternative solution: get the latLong from place name using Geocoder
Deprecation notice: Google Play Services version of the Places SDK for Android
Please refer this link
https://developers.google.com/places/android-sdk/autocomplete
A colleague of mine is currently working on implementing turn by turn directions into an app that is being developed for the company we are working in. I have been tasked with trying to assist him but neither of us have been able to make any progress.
He is using Mapbox to create the map. I have never used mapbox before so I am not much help.
He has code implemented that should give us turn by turn directions but it does not seem to be doing anything whatsoever.
Sorry if I am bringing up old questions or am not stating my situation clearly but this is the best I can explain myself. We have done much searching but nothing we found seems to help.
Here is the code that he has tried using that is supposed to implement turn by turn directions.
private void getRoute(Waypoint origin, Waypoint destination) throws ServicesException {
MapboxDirections client = new MapboxDirections.Builder()
.setOrigin(origin)
.setDestination(destination)
.setProfile(DirectionsCriteria.PROFILE_DRIVING)
.setSteps(true)
// .setOverview(DirectionsCriteria.OVERVIEW_FULL)
.setInstructions(DirectionsCriteria.INSTRUCTIONS_TEXT)
.setAccessToken("pk.eyJ1IjoibnRyY3N2ZyIsImEiOiJCUmc4OHhjIn0.shHWdNg3Q32QUHJ1nOCs3A")
.build();
client.enqueue(new retrofit.Callback<DirectionsResponse>() {
#Override
public void onResponse(Response<DirectionsResponse> response, Retrofit retrofit) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().getRoutes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
}
#Override
public void onFailure(Throwable t) {
Log.e(TAG, "Error: " + t.getMessage());
Toast.makeText(MainActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
public void onResponse(Response<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().getRoutes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
drawRoute(currentRoute);
}
private void drawRoute(DirectionsRoute route) {
// Convert LineString coordinates into LatLng[]
LineString lineString = LineString.fromPolyline(route.getGeometry(), Constants.OSRM_PRECISION_V5);
List<Position> coordinates = lineString.getCoordinates();
LatLng[] points = new LatLng[coordinates.size()];
for (int i = 0; i < coordinates.size(); i++) {
points[i] = new LatLng(
coordinates.get(i).getLatitude(),
coordinates.get(i).getLongitude());
}
Polyline polyline = mMapboxMap.addPolyline(new PolylineOptions()
.add(points)
.color(Color.RED)
.width(5));
directionsOn = true;
}
Any help would be very much appreciated.
Thanks in advance.
I'd highly recommend changing from Directions v4 to v5 found in Mapbox Java. Once you make the switch, you can work off this example found on our website. Make sure you are also passing in coordinates in the correct order, longitude is given first followed by latitude.
Dear friend mapbox provides detailed document with sample code snippets as well.
I have build a working app for my requirement by following mapbox turn by turn navigation documents.
please follow the link and let me know if you face any issues.
Link : https://www.mapbox.com/android-docs/navigation/overview/navigation-ui/
Here you can use NavigationView component to customise the mapbox turn by turn features.
So in my app I am making use of google map apis and I'm using Geocoding to determine the Address based on the user's current location. I was using the Geocoder Android Class but I've found that it truly works terribly. It's just not reliable. So I used a post I saw here at SO to create my own Geocoder. Problem is, I now don't know if I'm using server side or client side geocoding. This is kind of important because one has a limit and the other really doesn't. All of my code is in Android though.
Here's some code, this is within my "MyGeocoder" Class:
public List<Address> getFromLocation(double latitude, double longitude,
int maxResults) throws IOException, LimitExceededException {
if (latitude < -90.0 || latitude > 90.0) {
throw new IllegalArgumentException("latitude == " + latitude);
}
if (longitude < -180.0 || longitude > 180.0) {
throw new IllegalArgumentException("longitude == " + longitude);
}
if (isLimitExceeded(context)) {
throw new LimitExceededException();
}
final List<Address> results = new ArrayList<Address>();
final StringBuilder url = new StringBuilder(
"http://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=");
url.append(latitude);
url.append(',');
url.append(longitude);
url.append("&language=");
url.append(Locale.getDefault().getLanguage());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url.toString());
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
Gson gson = new Gson();
MyGeocodeResponse geocodeResponse = gson.fromJson(jsonResult, MyGeocodeResponse.class);
final Address current = new Address(Locale.getDefault());
if(geocodeResponse.getStatus().equals(STATUS_OK)) {
MyGeocode locGeocode= geocodeResponse.getResults().get(0);
String streetAddress = "";
for(MyAddressComponent component : locGeocode.getAddress_components()) {
for(String type : component.getTypes()) {
if(type.equals("locality")) {
current.setLocality(component.getLong_name());
}
if(type.equals("administrative_area_level_1")) {
current.setAdminArea(component.getLong_name());
}
if(type.equals("street_number")) {
if(streetAddress.length() != 0) {
current.setAddressLine(0, component.getLong_name() + " " + streetAddress);
} else {
streetAddress = component.getLong_name();
}
}
if(type.equals("route")) {
if(streetAddress.length() != 0) {
current.setAddressLine(0, streetAddress + " " + component.getShort_name());
} else {
streetAddress = component.getShort_name();
}
}
}
}
current.setLatitude(latitude);
current.setLongitude(longitude);
results.add(current);
}
Log.i("TEST", "Got it");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
Edit:
And I guess a further questions is, if this is server-side Geocoding, then can this code only be run 2,500 times per day period, or can it be run 2,500 times daily per user of the app? If it's the first option I'm still ok, but if it's the 2nd option I don't see how any app that wants to have a half-way big user base can use server-side geocoding without hitting that limit.
I now don't know if I'm using server side or client side geocoding
after looking to your code you wrote http://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=,so it is server side reverse geocoding as you are calling geocoding api by making an extra External http call.
if this is server-side Geocoding, then can this code only be run 2,500 times per day period, or can it be run 2,500 times daily per user of the app?
2,500 request limit is per IP address(basically it is mentioning 2500 request per day),yah this code only be run 2,500 times per day for all of your user.One thing you should keep in mind you are making http call to geocoder api so it doesn't matter from where you are making this call from server or from client.
you should have a look on this google link where they have mention "When to Use Client-Side Geocoding" and "When to Use Server-Side Geocoding".
Is it possible to use it as library project for my application,i want to use Android Google Maps real app search-ability functionality. How can i do it,is it possible?
Thanks in advance..
EDIT:
I have shown Google Map in my app successfully, I want to include Google Map search functionality means that I can able to search any location in the world in auto suggested field and by selecting a particular location and move marker to that location. so how can I?
I tried this and this but not getting auto suggested text why I don't know..
I want like:
step1: show map with search box
step2: while entering text it should auto suggest.
step3: when click on particular name move map to that location
You can easily provide that kind of search functionality by using Places API and Geocode API (Both will help you according to your usecase).
Read the below Documentation for your assistance.
GeoCode API
Places API
I would recommend to use Places API for your need ( As per my observation on your usecase). But you could also use geocode, If you needed.
Many working reference and examples are there.
For startup, below are my reference :
PlacesAPI AutoComplete feature, Hotel Finder with Autocomplete
GeocodeAPI Simple GeoCoding
NOTE :
I have suggested javascript API. But not sure whether it will help you in Android environment (I dont know anything about android environment).
No single Api can help you have to use multiple google api's
Step1. Implement Google Place autocomplete Read this
Step2. You have to geocode means you have to convert address to latitude and longitude check this
Step3. Now You can plot these lat-long on the map.
This works for me.
I think you should take a look at the Google Maps API for Android at https://developers.google.com/maps/documentation/android/
The Google Search Appliance doesn't have any mapping or geo search features right now.
This is how I did it ---
Android Manifest file should contain the following lines:
<uses-library
android:name="com.google.android.maps"
android:required="true" >
</uses-library>
<!-- You must insert your own Google Maps for Android API v2 key in here. -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="<put your api key value here>" />
Location XML file should have the following apart from anything extra:
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Location java file should have something like this:
View mapView = null;
private GoogleMap mMap;
mMap = supportMapFragment.getMap();
mapView = (View) view.findViewById(R.id.map);
SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
.findFragmentById(R.id.map);
if(mMap != null){
mMap.setMyLocationEnabled(true);
}
if(mMap != null)
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
new EditMap().execute("", String.valueOf(latLng.latitude), String.valueOf(latLng.longitude));
}
});
class EditMap extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
String address = args[0];
double latitude = Double.parseDouble(args[1]);
double longitude = Double.parseDouble(args[2]);
return editMap(address, latitude, longitude);
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
if(!result.equals(""))
ToastUtil.ToastShort(getActivity(), result);
else {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title(attvalue));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 11));
}
}
}
NOTE:
These are the minimal requirements for the setting of location as you choose from Map that fills the location in your text.
There is a background thread that runs as you long press the location in a map.
The listener defined for that is setOnMapLongClickListener as you see above.
The execution will place the marker to the exact location you chose to mark as set.
There will be a done button after you have chosen the location by a marker. This done button will confirm what you have chosen and will set that on a textfield for you.
The above code uses the method editMap to edit the map location.
The implementation is as done here:
private String editMap(String address, double latitude, double longitude ) {
String keyword = null;
try {
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
if(!address.equals("")){
keyword = address;
java.util.List<android.location.Address> result = geocoder
.getFromLocationName(keyword, 1);
if (result.size() > 0) {
lat = (double) result.get(0).getLatitude();
lng = (double) result.get(0).getLongitude();
attvalue = address;
} else {
return "Record not found";
}
} else {
String sUrl = "http://google.com/maps/api/geocode/json?latlng="+latitude+","+longitude+"&sensor=true";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(sUrl);
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
try{
JSONObject jsonObject = new JSONObject(data);
JSONArray results = jsonObject.getJSONArray("results");
JSONObject addressObject = results.getJSONObject(0);
JSONArray addressComp = addressObject.getJSONArray("address_components");
String city = "", state = "";
for(int i=0; i < addressComp.length(); i++){
JSONArray types = addressComp.getJSONObject(i).getJSONArray("types");
if(city.equals("") && types.getString(0).equals("locality"))
city = addressComp.getJSONObject(i).getString("long_name");
if(state.equals("") && types.getString(0).equals("administrative_area_level_1"))
state = addressComp.getJSONObject(i).getString("long_name");
if(!city.equals("") && !state.equals(""))
break;
}
attvalue = city + ", " + state;
} catch (JSONException e1) {
e1.printStackTrace();
}
lat = latitude;
lng = longitude;
}else{
return "Location Not Found";
}
}
} catch (IOException io) {
return "Connection Error";
}
return "";
}
I hope this is enough to help you out.
I'm working on integrating Google Maps into the app I'm working on and I've had a rather unpleasant time doing it thus far. Regardless, I finally got a SupportMapFragment displaying a map and set a location and zoom level.
Here is the functional bits of my code thus far:
#Override
public void onActivityCreated( Bundle savedInstanceState ) {
super.onActivityCreated( savedInstanceState );
Location location = BundleChecker.getExtraOrThrow( KEY_LOCATION, new Bundle[] { savedInstanceState, getArguments() } );
setLocation( location );
if ( checkGooglePlayServicesStatus() == ConnectionResult.SUCCESS ) {
setMapFragment( new SupportMapFragment() );
getActivity().getSupportFragmentManager().beginTransaction().add( R.id.location_detail_mapFrame, getMapFragment() ).commit();
}
populateAddress();
attachButtonListeners();
Runnable initMap = new Runnable() {
#Override
public void run() {
if ( checkGooglePlayServicesStatus() == ConnectionResult.SUCCESS ) {
try {
GoogleMap map = getMapFragment().getMap();
LatLng latLng = getLocation().getAddress().getLatLng( getActivity() );
CameraUpdate update = CameraUpdateFactory.newLatLngZoom( latLng, DEFAULT_MAP_ZOOM );
map.animateCamera( update );
}
catch (IOException e) {
Log.e( TAG, e.getMessage(), e );
Toast.makeText( getActivity(), "Unable to find location", Toast.LENGTH_SHORT ).show();
}
}
}
};
Handler handler = new Handler();
handler.postDelayed( initMap, 200 );
}
Also, I wrote a simple convenience method to get a LatLng from my Address model that you may criticize as well:
/*
* Convenience method to easily check if there is a valid lat & lng in this address
*/
public boolean hasLatLng() {
return getLatitude() != null && getLongitude() != null;
}
/*
* Convenience method for use with Google Maps API
*/
public LatLng getLatLng( Context context ) throws IOException {
LatLng latLng = null;
if ( hasLatLng() ) {
latLng = new LatLng( getLatitude(), getLongitude() );
}
else {
String locationString = getStreet() + ", " + AddressUtil.makeCityStateZipString( this );
Geocoder geoCoder = new Geocoder( context );
try {
List<android.location.Address> matches = geoCoder.getFromLocationName( locationString, 2 );
if ( matches != null && matches.size() > 0 ) {
double lat = matches.get( 0 ).getLatitude();
double lng = matches.get( 0 ).getLongitude();
latLng = new LatLng( lat, lng );
}
}
catch (IOException e) {
throw new IOException( e );
}
}
return latLng;
}
I'm aware that this code is not ideal and needs to be refactored. This is my first time working with Google Maps so please feel free to offer suggestions as to how I might do that as well. I experienced a lot of problems when trying to use the MapFragment as a in my layout XML, so I'm creating it programmatically.
The heart of the matter:
I was getting some bogus address data from the staging server and this resulted in the Address#getLatLng method returning null which caused an exception when calling CameraUpdateFactory.newLatLngZoom. After I got this exception, I was no longer able to get map data from Google. The map fragment is blank now and messages are displayed in logcat:
05-21 18:11:42.903: I/Google Maps Android API(15747): Failed to contact Google servers. Another attempt will be made when connectivity is established.
05-21 18:11:43.093: E/Google Maps Android API(15747): Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).
I have created a new api key and replaced the current one in my manifest with no change. The only changes I had made to the above code were to account for a null LatLng and I have since undone those changes in a pointless attempt to get my code back to a functional state.
Additionally, to make things a bit stranger, I built the sample maps project that is included with the Google Play Services Extras and it works perfectly (has a separate API key, btw).
What might I have done wrong here? Am I overlooking something obvious?
This problem is usually derived from a problem in referencing google-play-service library.
Take a look at this blog post I wrote on how to integrate Google Maps in your application, especially the first 3 steps:
Google Maps API V2
another cause of this could be that you haven't configured the Google API Console properly, so I suggest you to take a look at this guide as well:
Google Maps API V2 Key
another reason that may cause this is if you have some kind of problem in your permissions in the manifest file. You can look at the first guide for the needed permissions as well.
Use Something like this:
Update the google play services in the SDK.
Manually uninstall the App from device and restart the device.
i have tried it and its going perfectly bro
Also do one thing get the new api key to edited the new sh1 code from https://code.google.com/apis/console/
you can get your sh1 code from window- preference-android-buid
Making Google maps work is a Googlemare. This worked for me:
-Update Google play services with the Android Manager
-Make a fresh apikey with: Sha1 keystore (Window->preferences->Android->Build) and project package name. Do this at: https://code.google.com/apis/console/
Somebody had changed the package name and was foiling the app!!
Try this before you need anger management therapy thanks to google maps.