Some CameraUpdateFactory questions - android

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.

Related

Enabling search feature in google maps using Android Studio

I was trying to implement a simple search bar in google maps that points the map's camera to the location that is entered in the search box, I've attached the code but whenever I run it, The application ends up crashing. The code is given below. (Also I'm new to Android Development, Please do help me out).
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final int REQUEST_LOCATION_PERMISSION = 1009;
private GoogleMap mMap;
private ActivityMapsBinding binding;
private FusedLocationProviderClient mFusedLocationClient;
//These Clusters were used to manage the marker Clusters that had images on maps too
private ClusterManager mClusterManager;
//Same is the case with these clusters
private MyClusterManagerRenderer myClusterManagerRenderer;
//Instantiating the Firestore Database
FirebaseFirestore db;
// creating a variable
// for search view.
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initializing our search view.
searchView = findViewById(R.id.idSearchView);
// initializing our firebase firestore.
db = FirebaseFirestore.getInstance();
binding = ActivityMapsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//Getting the device location over here
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// 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);
//***** Searching Part starts from here*********
// adding on query listener for our search view.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// on below line we are getting the
// location name from search view.
String location = searchView.getQuery().toString();
// below line is to create a list of address
// where we will store the list of all address.
List<Address> addressList = null;
// checking if the entered location is null or not.
if (location != null || location.equals("")) {
// on below line we are creating and initializing a geo coder.
Geocoder geocoder = new Geocoder(MapsActivity.this);
try {
// on below line we are getting location from the
// location name and adding that location to address list.
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
// on below line we are getting the location
// from our list a first position.
Address address = addressList.get(0);
// on below line we are creating a variable for our location
// where we will add our locations latitude and longitude.
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
// on below line we are adding marker to that position.
mMap.addMarker(new MarkerOptions().position(latLng).title(location));
// below line is to animate camera to that position.
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
// at last we calling our map fragment to update.
mapFragment.getMapAsync(this);
}
private void addMapMarkers(){
}
private void getLastKnownLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if(task.isSuccessful()){
Location location = task.getResult();
}
}
});
}
/**
* 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;
// creating a variable for document reference.
DocumentReference documentReference = db.collection("MapsData").document("7QWDor9vozLaHdFYV9kh");
// calling document reference class with on snap shot listener.
documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
if (value != null && value.exists()) {
// below line is to create a geo point and we are getting
// geo point from firebase and setting to it.
GeoPoint geoPoint = value.getGeoPoint("geoPoint");
// getting latitude and longitude from geo point
// and setting it to our location.
LatLng location = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude());
// adding marker to each location on google maps
mMap.addMarker(new MarkerOptions().position(location).title("Name"));
// below line is use to move camera.
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
} else {
Toast.makeText(MapsActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show();
}
}
});
//Adding custom maps style over here
//******** THIS PART OF CODE EXCLUSIVELY DESIGNED TO FETCH THE CUSTOM MAPS.JSON TEMPLATE**********
enableMyLocation();
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.mapstyle));
if (!success) {
Log.e("MapsActivity", "Style parsing failed.");
}
} catch (Resources. NotFoundException e) {
Log.e("MapsActivity", "Can't find style. Error: ", e);
}
//******** MAP STYLING CODE ENDS OVER HERE **********
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
LatLng islamabad = new LatLng(33.68, 73.04);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Islamabad"));
//moving the camera position to Islamabad.
mMap.moveCamera(CameraUpdateFactory.newLatLng(islamabad));
}
//Getting the Users current Location
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
// Check if location permissions are granted and if so enable the
// location data layer.
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_LOCATION_PERMISSION:
if (grantResults.length > 0
&& grantResults[0]
== PackageManager.PERMISSION_GRANTED) {
enableMyLocation();
break;
}
}
}
}
Instead of implementing a SearchView, add the places API from google in your grade file as follows:
implementation 'com.google.android.libraries.places:places:2.3.0'
and use AutocompleteSupportFragment as follows:
try {
if (!Places.isInitialized()) {
Places.initialize(getActivity().getApplicationContext(), GlobalVariables.google_api_key);
}
// Initialize the AutocompleteSupportFragment.
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment) getChildFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.getView().setBackground(ContextCompat.getDrawable(getContext(), R.drawable.bginfo_whit));
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));
autocompleteFragment.setCountry("ET");
autocompleteFragment.setMenuVisibility(false);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng newLatLng = place.getLatLng();
mMap.moveCamera(CameraUpdateFactory.newLatLng(newLatLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
//Log.i(TAG, "An error occurred: " + status);
}
});
}
catch (Exception e)
{}

Added Markers on Map from an Array but only one marker is displayed

I'm trying to add multiple markers to the map, the coordinates of the marker are in an array List named locationList but as I run the project, it only displays the last index. I tried to solve this with the some related questions but it does not work. Here is the code.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
EditText et;
private ArrayList<Location> locationList ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=getIntent();
locationList= (ArrayList<Location>) intent.getSerializableExtra("location");
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);
et = (EditText) findViewById(R.id.et);
if (googleServiceAvailable()) {
Toast.makeText(this, "Perfect", Toast.LENGTH_LONG).show();
}
}
/**
* 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;
/* MarkerOptions opts = new MarkerOptions();
opts.position(new LatLng(14.559691260979879,121.02173693084717));
mMap.addMarker(opts);
MarkerOptions asd = new MarkerOptions();
asd.position(new LatLng(14.556659026561825,121.01744539642334));
mMap.addMarker(asd);*/
//loop for adding markers. I tried printing the indexes and got the total size
for(int i=1; i<locationList.size();i++)
{
LatLng latlng = new LatLng(locationList.get(i).getLatitude(),locationList.get(i).getLongitude());
mMap.addMarker(new MarkerOptions().position(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;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
private void goToLocationZoom(double lat,double lng,float zoom){
LatLng ll= new LatLng(lat,lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
//Using geoLocate
public void geoLocate(View view) throws IOException {
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(et.getWindowToken(),0);
String location = et.getText().toString();
Geocoder gc = new Geocoder(this);
List<Address> list = gc.getFromLocationName(location,1);
Address address = list.get(0);
String locality = address.getLocality();
Toast.makeText(this,locality,Toast.LENGTH_LONG).show();
double lat = address.getLatitude();
double lng = address.getLongitude();
goToLocationZoom(lat,lng,17);
}
If your list is 2 items long, your for loop is only running once and it's picking up the second item on it's first run through.
I think you've mixed up the indexes between 0 and 1. Java Lists are 0-based.
Initialize i to 0 and you should be good.
for(int i=0; i<locationList.size();i++)
{
Location l = locationList.get(i);
LatLng latlng = new LatLng(l.getLatitude(),l.getLongitude());
mMap.addMarker(new MarkerOptions().position(latlng));
}

Android google map Marker won't Show

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

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{

Adding Polyline through a timer on Google map in Android

I have a google map in which when user press 'start' button, a timer will start which will keep getting user's current location after every 10 seconds and will draw a polyline from previos to current location untill user hits the 'Stop tracking' button.
Now my is doing all fine except the polyline, it's not drawing the polyline thorugh a timer at all. And if i re-press the 'start' button it does ( add the poloyline from prev to current location, like my application will keep adding the polyline if i keep pressing start button but i don't want it this way). i want it to draw the line thorugh a timer not on the button press.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
Button start,stop,track_record;
GPSTracker gps;
ArrayList<String> cordsList= new ArrayList<String>();
ArrayList<LatLng> MarkerPoints;
ArrayList<Double> arrLat= new ArrayList<Double>();
ArrayList<Double> arrLng = new ArrayList<Double>();
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private final int TIME_INTERVAL = 10000;
Timer timer=new Timer();
double longitude,latitude;
private static LatLng prev = new LatLng(0,0);
int Flag = 0;
static int begin = 0;
private LatLng fixedBegin ;
private LatLng listPoints = new LatLng(0,0);
ArrayList<LatLng> listP= new ArrayList<LatLng>();
Handler m_handler;
Runnable m_handlerTask ;
int t=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
stop = (Button) findViewById(R.id.btn_stop);
track_record = (Button) findViewById(R.id.btn_TR);
// track record activity
track_record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplication(), "Your Tracking is started now", Toast.LENGTH_SHORT).show();
///////*************************************////////
// create class object
gps = new GPSTracker(MapsActivity.this);
timer.scheduleAtFixedRate(new TimerTask() {
#SuppressLint("DefaultLocale")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
LatLng current = new LatLng(latitude = gps.getLatitude(),longitude = gps.getLongitude());
if (begin == 0) {
fixedBegin = current;
// create marker
MarkerOptions marker = new MarkerOptions().position(fixedBegin).title("Begin ");
// Changing the color babyyy
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// adding marker
mMap.addMarker(marker);
// drawing polyline here
if(Flag==0) //when the first update comes, we have no previous points,hence this
{
prev=current;
Flag=1;
}
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(current, 16);
mMap.animateCamera(update);
mMap.addPolyline((new PolylineOptions())
.add(prev, current).width(6).color(Color.BLUE)
.visible(true));
prev=current;
current = null;
}
begin++;
Log.i("OK", "lat------ " + latitude);
Log.i("OK", "lng-------- " + longitude);
arrLat.add(latitude);
arrLng.add(longitude);
//////////// TRYING ///////////
// And it Worked :D
/*
if(Flag==0) //when the first update comes, we have no previous points,hence this
{
prev=current;
Flag=1;
}
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(current, 16);
mMap.animateCamera(update);
mMap.addPolyline((new PolylineOptions())
.add(prev, current).width(6).color(Color.BLUE)
.visible(true));
prev=current;
current = null;
*/
}
});
}
}, 0, TIME_INTERVAL);
// check if GPS enabled
if (gps.canGetLocation()) {
Log.i("ok", "Mai to hogaya true");
latitude = gps.getLatitude();
longitude = gps.getLongitude();
String longlat = String.valueOf(latitude) + ":" + String.valueOf(longitude);
cordsList.add(longlat);
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Sorry cant get location", Toast.LENGTH_LONG).show();
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
// gps.showSettingsAlert();
}
Log.i("Finall", "Location-> " + cordsList.toString());
}
}
);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Initializing
MarkerPoints = new ArrayList<>();
// 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);
// Toast on stop
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplication(), "Your Tracking is over now, yellow marker shows your destination", Toast.LENGTH_SHORT).show();
/////////
//yaha kaam karna hai abhi
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(gps.getLatitude(), gps.getLongitude())).title("REACHED :D ");
// Changing the color babyyy
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
// adding marker
mMap.addMarker(marker);
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
timer.cancel();
}
});
}
/**
* 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;
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
// Setting onclick event listener for the map
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Already two locations
if (MarkerPoints.size() >= 1) {
MarkerPoints.clear();
mMap.clear();
}
// Adding new item to the ArrayList
MarkerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
if (MarkerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}
// Below ELSE is not used any more due to the fetched location of user TADAAAA xD
else if (MarkerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
mMap.addMarker(options);
// Checks, whether start and end locations are captured
if (MarkerPoints.size() >= 1) {
//>>>> LatLng origin = MarkerPoints.get(0);
LatLng latLng1 = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
LatLng origin = latLng1;
LatLng dest = MarkerPoints.get(0);
// Getting URL to the Google Directions API
String url = getUrl(origin, dest);
Log.d("onMapClick", url.toString());
FetchUrl FetchUrl = new FetchUrl();
// Start downloading json data from Google Directions API
FetchUrl.execute(url);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(origin));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
}
}
);
}
private String getUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class FetchUrl extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
Log.d("Background Task data", data.toString());
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
Check the below two functions.
public void Draw_Map(List<LatLng> val) {
if(val.size() > 1) {
mGoogleMap.addPolyline(new PolylineOptions()
.add(val.get(mSource), val.get(mDestination))
.width(8)
.color(Color.BLACK));
mSource++;
mDestination++;
}
}
private void drawFinalPolygon() {
mLatLngList.add(mLatLngList.get(0));
PolygonOptions polygonOptions = new PolygonOptions();
polygonOptions.addAll(mLatLngList);
polygonOptions.strokeColor(Color.BLACK);
polygonOptions.strokeWidth(8);
polygonOptions.fillColor(Color.TRANSPARENT);
Polygon polygon = mGoogleMap.addPolygon(polygonOptions);
mGoogleMap.addMarker(new MarkerOptions()
.title("Marker Title here")
.snippet("Hello, I am marker snippet!")
.position(mLatLngList.get(0)));
}
Call Draw_Map() method whenever the location changes and call drawFinalPolygon() method when user click on stop tracking.

Categories

Resources