Google Maps Android -- Map suddenly no longer displayed - android

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.

Related

Can't get map fragment when trying to initialise the Map to render shapefile using OpenMap library

I have been trying to display a shapefile using openmap library. On click of a button on first activity, the application goes to the second activity (which is also the second page) but then it suddenly crashes.
I ran the debugger and realised that mapFragment variable was still null, it was getting the value from findFragmentById.
I ultimately intend to display a shapefile on the second page of my application.
public class ShapeFileParser extends AppCompatActivity implements OnMapReadyCallback {
GoogleMap mMap;
ShapeFile shapeFile;
File file;
public void setUpMap() {
try {
org.apache.commons.io.FileUtils.copyInputStreamToFile((ShapeFileParser.this.getAssets().open("healthsites.shp")), file);
} catch (IOException e) {
e.printStackTrace();
}
try {
shapeFile = new ShapeFile(file);
} catch (IOException e) {
e.printStackTrace();
}
try {
for (ESRIRecord esriRecord = shapeFile.getNextRecord(); esriRecord!=null; esriRecord = shapeFile.getNextRecord()){
String shapeTypeStr = ShapeUtils.getStringForType(esriRecord.getShapeType());
Log.v("myapp","shape type = " + esriRecord.getRecordNumber() + "-" + shapeTypeStr);
if (shapeTypeStr.equals("POLYGON")) {
// cast type after checking the type
ESRIPolygonRecord polyRec = (ESRIPolygonRecord)esriRecord;
Log.v("myapp","number of polygon objects = " + polyRec.polygons.length);
for (int i=0; i<polyRec.polygons.length; i++){
// read for a few layers
ESRIPoly.ESRIFloatPoly poly = (ESRIPoly.ESRIFloatPoly)polyRec.polygons[i];
PolygonOptions polygonOptions = new PolygonOptions();
polygonOptions.strokeColor(Color.argb(150,200,0,0));
polygonOptions.fillColor(Color.argb(150,0,0,150));
polygonOptions.strokeWidth(2.0f);
Log.v("myapp","Points in the polygon = " + poly.nPoints);
for (int j=0; j<poly.nPoints; j++){
//Log.v("myapp",poly.getY(j) + "," + poly.getX(j));
polygonOptions.add(new LatLng(poly.getY(j), poly.getX(j)));
}
mMap.addPolygon(polygonOptions);
Log.v("myapp","polygon added");
}
}
else {
Log.v("myapp","error polygon not found (type = " + esriRecord.getShapeType() + ")");
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeMap();
}
private void initializeMap() {
if (mMap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// mapFrag is null on checking with the debugger
mapFrag.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
}
}
This is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ShapeFileParser" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
I am just trying an example to render a shape file onto the second page but I feel I am going no where since last two days. Kindly suggest some input if any.
I am a newbie in android dev, please be patient with me. Many thanks!
The OpenMap Library is used for Java Swing and JFrame applications and can't be used in an Android application as far as I can tell. The Google Map SDK has everything you need to display Maps in an Android Application including getting device location, displaying Places info, setting map markers, polylines, and polygons. Getting location updates in the backgroud, etc... To set it up, create a new Maps Activity from the Gallery. It will generate all the needed files for you and give you a list of instructions to get an API Key so that Maps can be used in your app. Here is a question explaining the security of your api key that I answered a while back. Google Maps Docs explains all the basic functionality of how to get Maps setup. I would recommend you visit some YouTube Tutorials on how to set Maps up in your Android application.
<--EDIT-->
Here is an answer I found on Stack Overflow from about two years ago. It doesn't really use the OpenMap Libray, but it's a workaround. You can pull ShapeFile data and use it in Google Maps Polygon, Polyline, and LatLng classes and display those on a map in your android application.

Android Google Maps Direction Api - Api key restriction not working

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

Android Google Service Place picker setLatLngBounds() not working

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.

How to use Google maps search functionality api in my application?

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.

getFromLocationName() returns null on android tablet

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.

Categories

Resources