Android google map Marker won't Show - android

I'm new at android development. I'm trying to add a Google marker at my App map but it won't show. I can set a Marker if the Marker's lat & lng is a double number,but when i put the API data in it it won't show.Any suggestion? Thanks a lot.
#Override
public void onMapReady(final GoogleMap googleMap) {
this.googleMap = googleMap;
// Add a marker in Sydney and move the camera
getLocation();
// This marker will show at my app screen !
LatLng latLng = new LatLng(24.9992666, 121.5082287);
googleMap.addMarker(new MarkerOptions().position(latLng)
.title("This is office Marker")
);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
}
this.googleMap.setMyLocationEnabled(true);
HttpUtil.sendHttpRequest("http://113.10.198.159/appapi/getWIFIList", new HttpCallbackListener() {
#Override
public void onFinish(String response) {
Gson gson = new Gson();
JsonBean jsonBean = gson.fromJson(response, JsonBean.class);
Log.d(TAG, "【】【id】【】" + jsonBean.getResult().get(0).getId());
Log.d(TAG, "【】【merchant_id】【】" + jsonBean.getResult().get(0).getMerchant_id());
Log.d(TAG, "【】【merchant_name】【】" + jsonBean.getResult().get(0).getMerchant_name());
Log.d(TAG, "【】【city】【】" + jsonBean.getResult().get(0).getCity());
Log.d(TAG, "【】【area】【】" + jsonBean.getResult().get(0).getArea());
Log.d(TAG, "【】【address】【】" + jsonBean.getResult().get(0).getAddress());
Log.d(TAG, "【】【lat】【】" + jsonBean.getResult().get(0).getLat());
Log.d(TAG, "【】【lng】【】" + jsonBean.getResult().get(0).getLng());
Log.d(TAG, "【】【addTime】【】" + jsonBean.getResult().get(0).getAddTime());
Log.d(TAG, "【】【dlat】【】" + jsonBean.getResult().get(0).getDlat());
Log.d(TAG, "【】【dlng】【】" + jsonBean.getResult().get(0).getDlng());
Log.d(TAG, "【】【wificode】【】" + jsonBean.getResult().get(0).getWificode());
Log.d(TAG, "【】【upstream】【】" + jsonBean.getResult().get(0).getUpstream());
Log.d(TAG, "【】【downstream】【】" + jsonBean.getResult().get(0).getDownstream());
//// This marker can not show at my app screen
LatLng latLng = new LatLng(jsonBean.getResult().get(0).getDlat(), jsonBean.getResult().get(0).getDlng());
Marker marker = googleMap.addMarker(new MarkerOptions().position(latLng)
.title("This is Test Marker")
);
}
#Override
public void onError(Exception e) {
}
});
}
public class HttpUtil {
public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {
new Thread(new Runnable() {
#Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
String s1 = "lat";
String s2 = "24.9992666";
String s3 = "lng";
String s4 = "121.5082287";
RequestBody requestBody = new FormBody.Builder()
.add(s1, s2)
.add(s3, s4)
.build();
Request request = new Request.Builder()
.url(address)
.post(requestBody) //post
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
if (listener != null) {
// onFinish() method
listener.onFinish(responseData);
}
} catch (Exception e) {
if (listener != null) {
// onError() method
listener.onError(e);
}
}
}
}).start();
}
}

Is the map shoiwing up? What is inside your
getLocation();
function, if there is not something like the following, then add it
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Also remember to zoom in and out and pan the map around, may be the marker is plotted where you did not expect it to be.
if it still does not work, follow this tutorial, it must work.
google maps with marker

Are you sure you're getting the right value from the json? It may be returning a string. You might want to try converting it to the valueOf to get the desired type.
For a double it would be something like:
double lat = Double.valueOf(jsonBean.getResult().get(0).getDlat());

Related

Custom Map Tile Work in Chrome but not Android

I'm building an Android app that uses custom map tiles. I started out with a set that worked fine but only had limited zoom levels and area. Then I switched to another tile set that covered much more area but simply refuses to display in Android. I can see them in the Javascript Maps and there are no errors in my LogCat so I'm not sure what's going on.
Are there only certain image formats that the Android Map overlays support?
For reference, here are the two tile sets:
This one works both on the web and in Android:
http://mooproductions.org/vfrs/local.html
This one works on the web but simply doesn't render on Android:
http://mooproductions.org/vfrs/national.html
Here's he code I'm using to provide the tile sets:
public class VfrTileProvider extends UrlTileProvider
{
// private static final String BASE_URL = "http://www.mooproductions.org/vfrs/%d/%d/%d.png";
// private static final String BASE_URL = "http://mw1.google.com/mw-planetary/lunar/lunarmaps_v1/clem_bw/%d/%d/%d.jpg";
private static final String BASE_URL = "http://vfrmap.com/20170914/tiles/vfrc/%d/%d/%d.jpg";
public VfrTileProvider (int width, int height)
{
super(width, height);
}
#Override
public URL getTileUrl (int x, int y, int zoom)
{
int reversedY = (1 << zoom) - y - 1;
// String tileUrl = String.format(Locale.US, BASE_URL, zoom, x, reversedY);
String tileUrl = String.format(Locale.US, BASE_URL, zoom, reversedY, x);
Log.d("Tile Provider", tileUrl);
URL url = null;
try { url = new URL(tileUrl); }
catch (MalformedURLException e) { e.printStackTrace(); }
return url;
}
}
You can see commented out are the other URLs for tile sets that I use that work just fine. The creation of the tileUrl is a little different because this new tile set transposes the x and y in their url.
Here is the code I use to display the custom tiles:
#Override
public void onMapReady (GoogleMap googleMap)
{
_map = googleMap;
_map.setMapType(GoogleMap.MAP_TYPE_NONE);
VfrTileProvider tileProvider = new VfrTileProvider(256, 256);
_map.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
Criteria criteria = new Criteria();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }, REQUEST_LOCATION_PERMISSION);
return;
}
Location location = _locationManager.getLastKnownLocation(_locationManager.getBestProvider(criteria, false));
if (location != null)
{
_map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude()))
.zoom(10)
.build();
_map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
This is because wrong "User-Agent" property settings of URL url object in VfrTileProvider.getTileUrl(). You can set it to correct by setRequestProperty():
URL url = null;
try {
url = new URL(tileUrl);
try {
url.openConnection().setRequestProperty("User-Agent","<correct user agent name>");
} catch (IOException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
or just add System.setProperty("http.agent", ""); call to your public void onMapReady ():
#Override
public void onMapReady (GoogleMap googleMap)
{
System.setProperty("http.agent", "");
_map = googleMap;
...
}
I prefer second (System.setProperty("http.agent", "");) case.

Getting the phone number of nearby place

I've been following this tutorial on displaying nearby places, in my case I need nearby hospitals. I'm able to show my current location and display nearby hospitals. But what I want to do is add the telephone number of those hospitals being displayed. I've tried adding formatted_phone_number in my code but it doesn't display the correct phone number but instead displays "-NA-" which is the default in the event that there's no number available.
Any help would be greatly appreciated thanks!
Code Snippet of GetNearbyPlacesData class:
private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
for (int i = 0; i < nearbyPlacesList.size(); i++) {
Log.d("onPostExecute","Entered into showing locations");
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
String formatted_phone_number = googlePlace.get("formatted_phone_number");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
markerOptions.snippet(vicinity + formatted_phone_number);
mMap.addMarker(markerOptions);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
}
DataParser class:
public class DataParser {
public List<HashMap<String, String>> parse(String jsonData) {
JSONArray jsonArray = null;
JSONObject jsonObject;
try {
Log.d("Places", "parse");
jsonObject = new JSONObject((String) jsonData);
jsonArray = jsonObject.getJSONArray("results");
} catch (JSONException e) {
Log.d("Places", "parse error");
e.printStackTrace();
}
return getPlaces(jsonArray);
}
private List<HashMap<String, String>> getPlaces(JSONArray jsonArray) {
int placesCount = jsonArray.length();
List<HashMap<String, String>> placesList = new ArrayList<>();
HashMap<String, String> placeMap = null;
Log.d("Places", "getPlaces");
for (int i = 0; i < placesCount; i++) {
try {
placeMap = getPlace((JSONObject) jsonArray.get(i));
placesList.add(placeMap);
Log.d("Places", "Adding places");
} catch (JSONException e) {
Log.d("Places", "Error in Adding places");
e.printStackTrace();
}
}
return placesList;
}
private HashMap<String, String> getPlace(JSONObject googlePlaceJson) {
HashMap<String, String> googlePlaceMap = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity = "-NA-";
String formatted_phone_number = "-NA-";
String latitude = "";
String longitude = "";
String reference = "";
Log.d("getPlace", "Entered");
try {
if (!googlePlaceJson.isNull("name")) {
placeName = googlePlaceJson.getString("name");
}
if (!googlePlaceJson.isNull("vicinity")) {
vicinity = googlePlaceJson.getString("vicinity");
}
if (!googlePlaceJson.isNull("formatted_phone_number")) {
formatted_phone_number = googlePlaceJson.getString("formatted_phone_number");
}
latitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference = googlePlaceJson.getString("reference");
googlePlaceMap.put("place_name", placeName);
googlePlaceMap.put("vicinity", vicinity);
googlePlaceMap.put("formatted_phone_number", formatted_phone_number);
googlePlaceMap.put("lat", latitude);
googlePlaceMap.put("lng", longitude);
googlePlaceMap.put("reference", reference);
Log.d("getPlace", "Putting Places");
} catch (JSONException e) {
Log.d("getPlace", "Error");
e.printStackTrace();
}
return googlePlaceMap;
}
}
MapsActivity class:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 20000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
Button btnHospital = (Button) findViewById(R.id.btnHospital);
btnHospital.setOnClickListener(new View.OnClickListener() {
String Hospital = "hospital";
#Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
String url = getUrl(latitude, longitude, Hospital);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(MapsActivity.this,"Nearby Hospitals", Toast.LENGTH_LONG).show();
}
});
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0"); //dito yung api key nasa sticky note
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();
Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
}
In MapsActivity.class, function getUrl() is taking "Hospital" as one of the arguments which is not in the list of supported types. So, the result type is default, since it doesn't match any supported types.
The response will give you all the places nearby search request for places of type 'default'. To make a request to Nearby Places API to get nearby hospitals, pass hospital instead of Hospital.
In the code, you make a request to Nearby Places API, formatted_phone_number is not returned in response. For more information, refer to the documentation.
To get the phone number(formatted_phone_number or international_phone_number) make a request to Place Details API with the PlaceId.
To get more clarity, enter the url in the browser and look at the response.
Hope this helps you. Good luck :)

onMapReady not working in android

I have created a Map Activity in which I want that when the user types the name of a place, he is suggested various places. When the user makes any selection, the map should position on the selected location. I have used PlaceSelectionListener for the same. Though I am able to get the Latitude and Longitude, the map does not seem to position itself. It takes the location that was previously set. I have attached my code below for reference.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
MapDialog mapDialog;
Button button;
TextView textView;
LocationManager mLocationManager;
GooglePlacesAutocompleteAdapter dataAdapter;
EditText et;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.text_view);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setVisibility(View.INVISIBLE);
Location location = getLastKnownLocation();
if (location != null) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
textView.setVisibility(View.VISIBLE);
textView.setText(getAddress(getApplicationContext(), userLocation.latitude, userLocation.longitude));
}
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Turn on Location").setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(onGPS);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).setMessage("Turn on Location services to access the application");
int off = 0;
try {
off = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
if (off == 0) {
builder.show();
} else {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) this.getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(_placeSelectedListener);
}
#Override
protected void onResume() {
super.onResume();
Log.e("TAG", "onResume");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
private PlaceSelectionListener _placeSelectedListener = new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.e("TAG", "place is " + String.valueOf(place.getLatLng().latitude + " " + place.getLatLng().longitude));
final Place xyz=place;
getWindow().getDecorView().findViewById(R.id.map).invalidate();
final OnMapReadyCallback onMapReadyCallback = new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(xyz.getLatLng().latitude, xyz.getLatLng().longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(xyz.getLatLng(), 15));
Log.e("GAT","Address "+getAddress(getApplicationContext(),xyz.getLatLng().latitude, xyz.getLatLng().longitude));
}
};
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(onMapReadyCallback);
//Place model has all data about Location selected from search box
}
#Override
public void onError(Status status) {
}
};
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = getLastKnownLocation();
// service.getLastKnownLocation(provider);
Log.e("TAG", "onResume" + location);
if (location != null) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
Log.e("TAG", "Location is " + userLocation + " " + userLocation.latitude + " " + userLocation.longitude);
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(userLocation.latitude, userLocation.longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
Log.e("GAT","Address "+getAddress(getApplicationContext(),userLocation.latitude,userLocation.longitude));
}
}
private Location getLastKnownLocation() {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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 null;
}
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
public String getAddress(Context context, double lat, double lng) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<android.location.Address> addresses = geocoder.getFromLocation(lat, lng, 1);
android.location.Address obj = addresses.get(0);
/*String add = obj.getAddressLine(0);
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();*/
String add = obj.getAddressLine(0)+","+obj.getPostalCode()+" "+obj.getAdminArea()+" "+obj.getCountryCode();
return add;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return null;
}
}
}
I haven't tried it, but try to create onMapReady() to onConnected(), add buildGoogleApiClient() call from onCreate() to onMapReady()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
//buildGoogleApiClient();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
//add this here:
buildGoogleApiClient();
//LatLng loc = new LatLng(lat, lng);
//mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lng = mLastLocation.getLongitude();
mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}
}
You can use requestLocationUpdates(), and call removeLocationUpdates() when the first location comes in.
Here's a demo app which can help you to understand how maps api works: https://github.com/googlemaps/android-samples/tree/master/ApiDemos
Make sure you activity extends and implement these classes
... extends FragmentActivity implements OnMapReadyCallback
example, see the code below
public class LocationPickerActivity extends FragmentActivity implements OnMapReadyCallback{

Some CameraUpdateFactory questions

I have some questions of CameraUpdateFactory.
Q1 :
I am trying to do a function that when i click the button it executes function "mapList()"
My "mapList()" is just to change my camera position. // run successfully but not work!!!!
So I use the Google Map API's functions.
My code below -> mapList()
public void mapList(View view) {
Intent intentMap = new Intent(this, MapsActivity.class);
// start map component
LatLng tagCYCU = new LatLng(24.956867, 121.242846);
CameraPosition cameraPosition =
new CameraPosition.Builder()
.target(tagCYCU)
.zoom(17)
.build();
CameraUpdateFactory.newLatLng(tagCYCU) ;
CameraUpdateFactory.newCameraPosition(cameraPosition) ;
startActivityForResult(intentMap, 0);
}
Q2 :
In my Maps activity, I want to try to read the informations from other fragments.Because I need it to do something. ( also change camera position )
So I do this code , but always "ERROR" // null object
My code below -> MapsActivity()
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
TextView getTextAddress ;
Spinner getName ;
String addrRestaurant = "", nameRestaurant = "" ;
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
// Location
private LocationRequest locationRequest;
private Location currentLocation;
private Marker currentMarker, itemMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// ------------------------------- Get current location ---------------------------------
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
}
Location location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng currentHere = new LatLng(currentLatitude,currentLongitude) ;
mMap.addMarker(new MarkerOptions().position(currentHere).title("Current Here"));
// --------------------------------------------------------------------------------------
// ---------------------------- Tag all restaurants from SQLite--------------------------
String addrRestaurant = "" ;
getTextAddress = (TextView)findViewById(R.id.textViewAddress);
// what i get , camera change to that position
// bur textViewAddress is in other fragments !!
addrRestaurant = getTextAddress.getText().toString();
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
Restaurant.KEY_ID + "," +
Restaurant.KEY_name + "," +
Restaurant.KEY_type + "," +
Restaurant.KEY_price + "," +
Restaurant.KEY_phone + "," +
Restaurant.KEY_addr + "," +
Restaurant.KEY_score +
" FROM " + Restaurant.TABLE;
Cursor cursor = db.rawQuery(selectQuery, null);
int sizeDB = (int) DatabaseUtils.queryNumEntries(db, "Restaurant");
String infoAddress = "", infoName = "" ;
for( int indexDB = 0 ; indexDB < sizeDB ; indexDB ++ ) {
cursor.moveToPosition(indexDB);
infoName = cursor.getString(cursor.getColumnIndex(Restaurant.KEY_name));
infoAddress = cursor.getString(cursor.getColumnIndex(Restaurant.KEY_addr)) ;
Geocoder geoCoder = new Geocoder(this);
List<Address> addressLocation ;
try {
addressLocation = geoCoder.getFromLocationName(infoAddress, 1);
double latitude = addressLocation.get(0).getLatitude();
double longitude = addressLocation.get(0).getLongitude();
LatLng tag = new LatLng(latitude, longitude);
addMarker(tag, "Foody Restaurants",infoName ); // get mark !
if(addrRestaurant.equals(infoAddress) == true){
// change camera position according to what i get fom other activity
mMap.moveCamera(CameraUpdateFactory.newLatLng(tag));
moveMap(tag);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
// --------------------------------------------------------------------------------------
}
private void moveMap(LatLng place) {
CameraPosition cameraPosition =
new CameraPosition.Builder()
.target(place)
.zoom(17)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
private void addMarker(LatLng place, String title, String snippet) {
BitmapDescriptor icon =
BitmapDescriptorFactory.fromResource(R.mipmap.ic_tag);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(place)
.title(title)
.snippet(snippet)
.icon(icon);
mMap.addMarker(markerOptions);
}
Locat
Process: com.example.user.foody, PID: 2896
java.lang.NullPointerException:
Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
at com.example.user.foody.MapsActivity.onMapReady(MapsActivity.java:121)
MapsActivity.java:121 -> ( addrRestaurant = getTextAddress.getText().toString(); )
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
I really need help !! Please :( thank you ..
You can check this sample on GitHub on how to change the camera position for the map. This code snippet runs when the Animate To Sydney button is clicked.
public void onGoToSydney(View view) {
if (!checkReady()) {
return;
}
changeCamera(CameraUpdateFactory.newCameraPosition(SYDNEY), new CancelableCallback() {
#Override
public void onFinish() {
Toast.makeText(getBaseContext(), "Animation to Sydney complete", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onCancel() {
Toast.makeText(getBaseContext(), "Animation to Sydney canceled", Toast.LENGTH_SHORT)
.show();
}
});
}
Regarding Fragments, check the documentation about adding a Fragment object to the Activity that will handle the map.
Check this SO post on how to fix and what are the possible causes of the NullPointerException.
"The best way to avoid this type of exception is to always check for null when you did not create the object yourself." If the caller passes null, but null is not a valid argument for the method, then it's correct to throw the exception back at the caller because it's the caller's fault.

Unable to plot marker on the map using json

The marker is not showing on the map, json data is totally fine and i can see that while debugging.but marker is not showing on the map
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
public GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void onMapSearch (View view) throws IOException {
//hide button when button is pressed
InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//preview the entered address as an Tost in bar
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
//this will animate camera and zoom 12.0f
mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));
//further address search codes
List<Address> addressList = null;
//if nothing will be entered in the edit-text will not show a toast rather than crashing of thekha app
if (locationSearch.getText().toString().equals("")){
Toast.makeText(this,"Bitch please enter A Value",Toast.LENGTH_LONG).show();
}
else {
//process of exception handling and finding location
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
//if address is greater than one then these processes will happen
if(addressList.size()>0) {
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(latLng)
.title(location + " is Here- ")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(this, location+" is here, Zoom In or Zoom Out to make your Thekha Visible ", Toast.LENGTH_LONG)
.show(); //popup type to show entered data
}
else {
//process where entered entry will not gonna find , this will gonna a toast to show popup
Toast.makeText(this,"Entered Address Not Found", Toast.LENGTH_LONG).show();
}
}
}
}
private class RetriveMarkerTask extends AsyncTask<StringBuilder,Void,StringBuilder> {
private Context context;
private String jsonData;
public RetriveMarkerTask(Context context) {
this.context = context;
}
#Override
protected StringBuilder doInBackground(StringBuilder... stringBuilders) {
android.os.Debug.waitForDebugger();
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
//connect to the web service
URL url = new URL("http://www.loofre.com/api-for-webservice/?debug=true&action=getLocations");
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
//This will read the json data into string builder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
this.jsonData = new String(buff);
} catch (IOException e) {
return null;
} catch (Exception ex) {
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
return json;
}
}
#Override
protected void onPostExecute(StringBuilder stringBuilder) {
super.onPostExecute(stringBuilder);
try {
((MapsActivity)context).createMarkerFromJson(this.jsonData);
}catch (JSONException e){
e.printStackTrace();
}
}
}
void createMarkerFromJson (String json) throws JSONException {
// de-derialize the json string into an array of objects
JSONArray jsonArray = new JSONArray(json);
for (int i =0; i<jsonArray.length(); i++){
//create marker of each place in the json data
JSONObject jsonObject = jsonArray.getJSONObject(i);
String placeName = jsonObject.getString("name");
String placeAddress = jsonObject.getString("address");
double latitude = jsonObject.getJSONArray("latlang").getDouble(0);
double longitude = jsonObject.getJSONArray("latlang").getDouble(1);
LatLng loc = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 13));
mMap.addMarker(new MarkerOptions()
.title(placeName)
.snippet(placeAddress)
.position(loc)
);
}
}
//OnReady map starts here when we can enter or add Marker to the map
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
RetriveMarkerTask markerTask = new RetriveMarkerTask(this);
markerTask.execute();
}catch (Exception e){
Toast.makeText(this,"Can not fetch data",Toast.LENGTH_LONG).show();
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(this, android.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;
}
//tool bar and other tool related on map uiSettings
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
}
Instead of passing the context to your task and then casting the context back to call a function, why not just pass the mMap in your constructor and then move your createMarkerFromJson function inside of your AsyncTask class. If the Json data coming back is correct, this will help us verify that your marker is being added to the correct thing. Does your call to moveCamera occur?

Categories

Resources