I am using PlacePicker in my App. All of sudden its behaving badly. When its launched its pointing to (0.0, 0.0) lat lng.
I am not sure if Google service changed something. earlier it was working all fine since from 3 days its not working.
Am I doing anything wrong here
This is How I am launching Activity.
private void launchPlacePicker(double latitude, double longitude) {
try {
showProgress(true);
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Log.d(TAG, " launchPlacePicker " + latitude + " " + longitude);
builder.setLatLngBounds(MapUtils.getLatLngBounds(new LatLng((double) latitude, (double) longitude)));
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
showProgress(false);
Log.e(TAG, "GooglePlayServicesRepairableException", e);
} catch (GooglePlayServicesNotAvailableException e) {
showProgress(false);
Log.e(TAG, "GooglePlayServicesNotAvailableException", e);
}
}
This is how I am creating LatLngBounds
public static LatLngBounds getLatLngBounds(LatLng center) {
double radius = 100;
LatLng southwest = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 225);
LatLng northeast = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 45);
return new LatLngBounds(southwest, northeast);
}
and I tried to create LatLngBounds like below, still same result.
public static LatLngBounds getLatLngBounds(LatLng center) {
LatLngBounds.Builder builder = LatLngBounds.builder();
builder.include(center);
return builder.build();
}
could some one help me
Unfortunately you are going to have to wait for Google to fix the issue in a future release of Google Play Services.
There is not anything wrong with your code, the latest update of Google Play Services causes some serious issues with the Place Picker UI widget. I first noticed the setLatLngBounds() method no longer works in Google Play Services 9.0.82. In 9.0.83, the search icon disappeared.
See my post regarding this issue: Android PlacePicker no longer has Search icon after updating to Google Play Services 9.0.83
See these bug reports from the Google Maps API bug and feature website:
Bug: Search Icon not visible in the latest play service update (Version:9.0.83) -----
Bug: Place Picker not showing search icon. -----
PlacePicker search icon is gone after updating to Google Play Services 9.0.83
You can somewhat work around the issue by not invoking the setLatLngBounds() method. PlacePicker will default to your current location. I lost some functionality in my app, but it was better than having the end user try to pinch and pan their way back from the Atlantic Ocean. For me, the missing search icon is still my major issue.
Related
I'm stuck on code to proceed next step in my android project. I severely try to find a sample code but couldn't find it yet. This is code that I have to add the KML layer to a google map in android studio API 29.i want to create a new field in KML layer attribute then field select and its data save to the Firebase in real-time. And also retrieve save data to show on the map as pop-out window. Please give me a sample code or link to resolve.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
KmlLayer layer = new KmlLayer(mMap,R.raw.testkml, getApplicationContext());
layer.addLayerToMap();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Add a marker in Sydney and move the camera
LatLng homagama = new LatLng(6.8440, 80.0024);
// mMap.addMarker(new MarkerOptions().position(homagama).title("Homagama"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(homagama));
float zoomLevel = (float) 13.0;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(homagama, zoomLevel));
You can access KML properties by utilizing the getProperty() function. You can also call hasProperty() to check if it exists. You can check the sample on Google Maps KML documentation: https://developers.google.com/maps/documentation/android-sdk/utility/kml#properties
I hope this helps!
When we are setting a Key restriction to NONE for Google Maps Direction Api, It works fine.
But When we set Key restriction to Android apps and provide a proper Package name & SHA-1 certificate - It says Request Declined from Google Api response.
Any known solution to this?
Directions API is a web service. The restrictions that will work with an API keys for web services are IP restrictions.
It is supposed that web services requests are executed on your backend servers. If you need to restrict an API key, the workaround is to create an intermediate server. Your Android application should send requests to the intermediate server, intermediate server should send requests to Google and pass responses back to your app. In this case you can restrict an API key by IP address of your intermediate server.
Have a look at this document:
https://developers.google.com/maps/faq#using-google-maps-apis
Hope this clarifies your doubt.
You will usually have more than one certificate. One for debug and one for release.
Ensure that you add both fingerprints or that the certificate fingerprint you are using matches the one for the buildType you specified
Please try with
compile 'com.akexorcist:googledirectionlibrary:1.1.1'
flow the doc or try this method
And 2nd method Set CameraWithCoordinationBounds for animate Camera:
private void drawMap(double s_lat,double s_lng,double e_lat,double e_lng) {
GoogleDirectionConfiguration.getInstance().setLogEnabled(true);
Log.e("map", "++");
List<LatLng> waypoints = Arrays.asList(
new LatLng(22.626390800000003, 88.4313014), new LatLng(22.619708499999998, 88.4369083)
);
GoogleDirection.withServerKey("AIz... your google api key")
.from(new LatLng(s_lat, s_lng))
.and(waypoints)
.to(new LatLng(e_lat, e_lng))
.transportMode(TransportMode.DRIVING)
.execute(new DirectionCallback() {
#Override
public void onDirectionSuccess(Direction direction, String rawBody) {
if (direction.isOK()) {
mMap.setMinZoomPreference(8f);
com.akexorcist.googledirection.model.Route route = direction.getRouteList().get(0);
int legCount = route.getLegList().size();
for (int index = 0; index < legCount; index++) {
Log.e("map", "++++" + index);
Leg leg = route.getLegList().get(index);
// mMap.addMarker(new MarkerOptions().position(leg.getStartLocation().getCoordination()));
if (index == 0) {
Log.e("position","0" + leg.getStartLocation().getCoordination());
// mMap.addMarker(new MarkerOptions().position(leg.getEndLocation().getCoordination()).title("User"));
mMap.addMarker(new MarkerOptions().position(leg.getStartLocation().getCoordination()).icon(BitmapDescriptorFactory
.fromResource(R.drawable.start_pointer)));
} else if (index == legCount - 1) {
// mMap.addMarker(new MarkerOptions().position(leg.getEndLocation().getCoordination()).title("User"));
mMap.addMarker(new MarkerOptions().position(leg.getEndLocation().getCoordination()).icon(BitmapDescriptorFactory
.fromResource(R.drawable.stop_pointer)));
} else {
mMap.addMarker(new MarkerOptions().position(leg.getEndLocation().getCoordination()).icon(BitmapDescriptorFactory
.fromResource(R.drawable.user_point)));
}
List<Step> stepList = leg.getStepList();
ArrayList<PolylineOptions> polylineOptionList = DirectionConverter.createTransitPolyline(MainActivity.this, stepList, 5, Color.RED, 3, Color.BLUE);
for (PolylineOptions polylineOption : polylineOptionList) {
mMap.addPolyline(polylineOption);
}
}
setCameraWithCoordinationBounds(route); // animateCamera
}
}
#Override
public void onDirectionFailure(Throwable t) {
Log.e("error", t.getLocalizedMessage() + t.getMessage() + "");
// Do something
}
});
}
private void setCameraWithCoordinationBounds(com.akexorcist.googledirection.model.Route route) {
LatLng southwest = route.getBound().getSouthwestCoordination().getCoordination();
LatLng northeast = route.getBound().getNortheastCoordination().getCoordination();
LatLngBounds bounds = new LatLngBounds(southwest, northeast);
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
}
I've used MapTiler to create some tiles that I'm trying to overlay onto a Google map with android and not having much luck. The Android documentation is pretty sparse on this topic but I've done what I think should work, yet I'm not seeing the tiles when I zoom in to the correct level. I'm trying to make the overlay happen in the onMapReady() callback, should I be doing that somewhere else?
Here's the code I have for the onMapReady method:
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMyLocationEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(44.481705,-114.9378269)).zoom(16).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mTileOverlay = googleMap.addTileOverlay(new TileOverlayOptions()
.tileProvider((new UrlTileProvider(256, 256) {
#Override
public URL getTileUrl(int x, int y, int zoom) {
String s = "http://www.example.com/tiles/"+zoom+"/"+x+"/"+y+".png";
// added this logging to see what the url is
Log.d("home", s);
try {
return new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
}
})));
}
any ideas here?
TIA
EDIT: I've adding some logging to see what 's' (my url) is returning, and it's returning the correct url and my server is serving up the tiles correctly from that url but still not seeing anything on the map in android.
It turns out I had a toast in my getTileUrl() method that was preventing the images from being returned. When I removed that, the tiles were served correctly.
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.
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.