Enabling search feature in google maps using Android Studio - android

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

Related

Viewing Location on google map sending Latitude and Longitude

I want to view the location on google map my app get the latitude and longitude of the location but the location does not show in google map. I used firebase database to store latitude and longitude
here is the code of map activity
public class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationButtonClickListener, GoogleMap.OnMyLocationClickListener, OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
// TODO: Before enabling the My Location layer, you must request
// location permission from the user. This sample does not include
// a request for location permission.
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;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
}
#Override
public void onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
}
Use this method and pass 4 parameter to this given method. First it will navigation to a particular place also add marker of that place.
Example:
public static Marker addPinPoint(GoogleMap map, Marker locationMarker, double selectLatitude, double selectLongitude){
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(locationLatitude, locationLongitude), fZoom));
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
Bitmap iconImage = ResourceUtil.getBitmap(App.getInstance().getContext(), R.drawable.icon_location_center); // your location icon
BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(iconImage);
locationMarker = map.addMarker(new MarkerOptions()
.anchor(0.0f, 1.0f)
.icon(icon)
.position(new LatLng(selectLatitude, selectLongitude)));
return locationMarker;
}
Use the following code to show marker on a specific latitude and longitude, on your onMapReady function:
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude,longitude));
mMap.addMarker(marker);
The latitude and longitude should be the one you fetch from Firebase.

Retrieve saved LatLong value from Firebase and show in marker

I have previously asked the similar question where I had issue with saving the data in the firebase cloud. I managed to store the latitude & longitude data in the firebase database using following code
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
// Return null here, so that getInfoContents() is called next.
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Inflate the layouts for the info window, title and snippet.
View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
(FrameLayout)findViewById(R.id.map), false);
TextView title = ((TextView) infoWindow.findViewById(R.id.title));
title.setText(marker.getTitle());
TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet));
snippet.setText(marker.getSnippet());
return infoWindow;
}
});
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
}
// Gets the current location of the device, and positions the map's camera.
private void getDeviceLocation() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = database.getReference();
Intent intent = getIntent();
callingActivity = intent.getIntExtra( "callingActivity",0 );
//If the map has been called from ScanActivity
if (callingActivity == 1) {
// Get the best and most recent location of the device
if (mLocationPermissionGranted) {
mLastKnownLocation = LocationServices.FusedLocationApi
.getLastLocation( mGoogleApiClient );
scanString = intent.getStringArrayListExtra( "beaconList" );
nameList = intent.getStringArrayListExtra( "nameList" );
addressList = intent.getStringArrayListExtra( "addressList" );
RssiList = intent.getIntegerArrayListExtra( "RssiList" );
for ( int i=0; i < scanString.size(); i++) {
addBeacon.name = nameList.get( i );
addBeacon.address = addressList.get( i );
addBeacon.Rssi = RssiList.get( i );
addBeacon.latitude = mLastKnownLocation.getLatitude();
addBeacon.longitude = mLastKnownLocation.getLongitude();
databaseReference.child( "foo" ).child(addBeacon.address).setValue( addBeacon);
}
}
}
But the problem is when I try to retrieve the location I see is my device's location instead of the saved latlong value in the firebase data base. I have 2 calling activities i.e. 1 is for storing the lat long to firebase and 2 for retrieving it. I can successfully save the value under unique id and update it whereas I am unable to retrieve the latlong. I am using following code for retrieval
else {
DatabaseReference latlong= FirebaseDatabase.getInstance().getReference().child( "foo" ).child( "08:9E:08:B4:57:18" );
mFirebaseDatabase.keepSynced(true);
al ValueEventListener beaconListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
LatLng newLocation = new LatLng(
dataSnapshot.child("latitude").getValue(Long.class),
dataSnapshot.child("longitude").getValue(Long.class));
//LatLng mRetrieved = new LatLng(dataSnapshot.getValue(beacon.class).latitude, dataSnapshot.getValue(beacon.class).longitude);
//mLastKnownLocation.setLatitude( dataSnapshot.getValue(beacon.class).latitude );
// mLastKnownLocation.setLatitude(60.192059);
mMap.addMarker( new MarkerOptions()
.position( newLocation)
.title( dataSnapshot.getKey()));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
databaseReference.addValueEventListener( beaconListener );
Here i am changing the lat long value of 1 particular child name "08:9E:08:B4:57:18" manually in database to check if i can see the marker in the map at that location but it just shows my device's current location.
I can provide further screen shot of my database n the application if required. Thanks in advance. Hope to have some valuable pointers.
Please add this code after adding marker, so that the marker will move to the location which you added
try {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(lat, lng));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(12);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
} catch (Exception e) {
Log.getStackTraceString(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));
}

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.

PinPoint on Google Maps and display the map in Activity

i am using google maps v2 and i'm new to it, what i'm doing is i open the map by pressing a button, the thing is that i need to pinpoint a certain location on the map and get its longitude and latitude to display the map again in another activity with the pinpointed location.
i'm a bit confused on how to manipulate google maps and how to display it in other activity, what do i need to add to the following code bellow??
here is my map code:
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
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;
}
mMap.setMyLocationEnabled(true);
Location currentLocation = mMap.getMyLocation();
if (currentLocation != null) {
updateLocation(currentLocation);
} else {
Log.d(getClass().getName(), "Current location is NULL");
}
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else {
LocationListener locationListener = new MyLocationListener();
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
return;
}
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, locationListener);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 1, locationListener);
Location locationGPS = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNet = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location loc;
long GPSLocationTime = 0;
if (null != locationGPS) {
GPSLocationTime = locationGPS.getTime();
}
long NetLocationTime = 0;
if (null != locationNet) {
NetLocationTime = locationNet.getTime();
}
if (0 < GPSLocationTime - NetLocationTime) {
loc = locationGPS;
} else {
loc = locationNet;
}
if (loc != null) {
updateLocation(loc);
}
//LatLng sydney = new LatLng(-33.867, 151.206);
}
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
updateLocation(loc);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
public void updateLocation(Location loc) {
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v(getClass().getName(), longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(getClass().getName(), latitude);
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(this, Locale.ENGLISH);
List<Address> addresses;
/*try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0) {
Log.d(getClass().getSimpleName(), (addresses.get(0).getLocality() == null ? "Null" : addresses.get(0).getLocality()));
cityName = addresses.get(0).getLocality();
}
} catch (IOException e) {
e.printStackTrace();
}*/
String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
+ cityName;
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
LatLng myLocation = new LatLng(loc.getLatitude(), loc.getLongitude());
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;
}
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 13));
mMap.addMarker(new MarkerOptions()
.title(cityName)
.snippet("My Location")
.position(myLocation));
}
}
If by pinpoint you mean tap to add a point on the map then use the code :
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
mMap.clear();
mMap.addMarker(new MarkerOptions().position(point));
//To Send this point to second mapsActivity
Intent i=new Intent(MapsActivity.this,MapsActivity1.class);
Bundle args = new Bundle();
args.putParcelable("POINT", point);
i.putExtra("bundle",args);
startActivity(i);
}
});
To create another map activity just right click on "app" folder->New->Google->Google MapsActivity.
A new Activity will be added.
Inside the new MapsActivity's onCreate() get this point by :
Bundle bundle = getIntent().getParcelableExtra("bundle");
LatLng markerPoint = bundle.getParcelable("POINT");
Inside the second mapsActivity's setUpMapIfNeeded() :
mMap.addMarker(new MarkerOptions().position(markerPoint));
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(markerPoint, 10));
Here 10 is the zoomlevel adjust it accordingly.
You can get LatLongs of marker by marker.getPosition(). just send these values via intent extras to your next activity and display it again on the map in that activity.

Categories

Resources