I'm making a search bar with google maps.
If I try to search somewhere the app will shutdown
And this is the error I get
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at com.example.yoons.honey.RealMap.onMapSearch(RealMap.java:71)
map.java
public class RealMap extends AppCompatActivity implements OnMapReadyCallback {
private Button searchButton;
GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.real_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
searchButton = new Button(this);
searchButton.setOnClickListener(search);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
private View.OnClickListener search=new View.OnClickListener(){
public void onClick(View v){
onMapSearch(v);
}
};
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addressList != null && addressList.size() != 0) {
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
} else {
Toast.makeText(getApplicationContext(), "location not found", Toast.LENGTH_SHORT).show();
}
}
}
}
I don't know why my code won't work
I copied most of the code on the internet
It's the most common search bar code I think but it doesn't work for me
Pass the googleMap reference to you variable mMap as:-
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
Related
I am making a map application where I am showing route between two points.
In this I am retrieving latitude and longitude from Nearby places(Google). All good up to this point but i don't get the directions. It shows bout points in map but nothing happens there.
I checked the console and i have no errors. I have looked on Google for a solution but so far i have found nothing. I have already tried to debug the code.
This is the ViewDirections code:
private GoogleMap mMap;
FusedLocationProviderClient fusedLocationProviderClient;
LocationCallback locationCallback;
LocationRequest locationRequest;
Location mLastLocation;
Marker mCurrentMarker;
Polyline polyline;
IGoogleAPIService mService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_directions);
// 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);
mService = Common.getGoogleAPIServiceScalars();
buildLocationRequest();
buildLocationCallBack();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
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) {
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
#Override
protected void onStop() {
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
super.onStop();
}
private void buildLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setSmallestDisplacement(10f);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
private void buildLocationCallBack() {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mLastLocation = locationResult.getLastLocation();
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude()))
.title("Your position")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mCurrentMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude())));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));
//create marker destination
LatLng destinationLatLng = new LatLng(Double.parseDouble(Common.currentResult.getGeometry().getLocation().getLat()),
Double.parseDouble(Common.currentResult.getGeometry().getLocation().getLng()));
mMap.addMarker(new MarkerOptions()
.position(destinationLatLng)
.title(Common.currentResult.getName())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
drawPath(mLastLocation,Common.currentResult.getGeometry().getLocation());
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
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) {
return;
}
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
mLastLocation = location;
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude()))
.title("Your position")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mCurrentMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude())));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));
//create marker destination
LatLng destinationLatLng = new LatLng(Double.parseDouble(Common.currentResult.getGeometry().getLocation().getLat()),
Double.parseDouble(Common.currentResult.getGeometry().getLocation().getLng()));
mMap.addMarker(new MarkerOptions()
.position(destinationLatLng)
.title(Common.currentResult.getName())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
drawPath(mLastLocation,Common.currentResult.getGeometry().getLocation());
}
});
}
private void drawPath(Location mLastLocation, com.example.osim4.travelonbucovina.Model.Location location) {
//clear all polyline
if(polyline !=null)
polyline.remove();
String origin = new StringBuilder(String.valueOf(mLastLocation.getLatitude())).append(",").append(String.valueOf(mLastLocation.getLongitude()))
.toString();
String destination = new StringBuilder(location.getLat()).append(",").append(location.getLng())
.toString();
mService.getDirections(origin,destination)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
new ParserTask().execute(response.body().toString());
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}
private class ParserTask extends AsyncTask<String,Integer,List<List<HashMap<String,String>>>> {
AlertDialog waitingDialog = new SpotsDialog(ViewDirections.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
waitingDialog.show();
waitingDialog.setMessage("Please waiting ....");
}
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
JSONObject jsonObject;
List<List<HashMap<String, String>>> routes = null;
try{
jsonObject = new JSONObject(strings[0]) ;
DirectionJSONParser parser = new DirectionJSONParser();
routes = parser.parse(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
super.onPostExecute(lists);
ArrayList points = null;
PolylineOptions polylineOptions = null;
for(int i=0;i<lists.size();i++)
{
points = new ArrayList();
polylineOptions = new PolylineOptions();
List<HashMap<String,String>> path = lists.get(i);
for(int j=0;j<lists.size();j++)
{
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat,lng);
points.add(position);
}
polylineOptions.addAll(points);
polylineOptions.width(12);
polylineOptions.color(Color.RED);
polylineOptions.geodesic(true);
}
polyline = mMap.addPolyline(polylineOptions);
waitingDialog.dismiss();
}
}
I am a beginner in Android programming. I already looked at similar questions and answers but I still can't figure out why this doesn't work. When I try this on the emulator and click a location, no marker appears. This is my code:
Edit: I get a marker when I click now with the following code. It only gives me a runtime exception (NullPointer exception) when I click the map the second time:
public class MapViewFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map_view, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
Context context = getActivity().getApplicationContext();
final LocationsDB locationsDB = new LocationsDB(context);
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng point) {
// Drawing marker on the map
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(point);
markerOptions.title(point.latitude + " : " + point.longitude);
googleMap.clear();
googleMap.animateCamera(CameraUpdateFactory.newLatLng(point));
googleMap.addMarker(markerOptions);
// Create location object
Location location = new Location(point.latitude, point.longitude);
// add location to SQLite database
locationsDB.insert(location);
}
});
}
});
return rootView;
}
}
Log messages:
7-20 07:33:00.076 5359-5359/? W/RcsService: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.rcs.service.service.a.a()' on a null object reference
at com.google.android.rcs.service.e.b(SourceFile:43)
at com.google.android.rcs.service.service.JibeService.onDestroy(SourceFile:162)
at android.app.ActivityThread.handleStopService(ActivityThread.java:3569)
at android.app.ActivityThread.-wrap26(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1703)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
07-20 07:33:00.079 5359-5359/? E/ActivityThread: Service com.google.android.rcs.service.service.JibeService has leaked IntentReceiver com.google.android.rcs.service.provisioning.RcsReconfigurationSmsReceiver#741339 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Service com.google.android.rcs.service.service.JibeService has leaked IntentReceiver com.google.android.rcs.service.provisioning.RcsReconfigurationSmsReceiver#741339 that was originally registered here. Are you missing a call to unregisterReceiver()?
at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:1310)
at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:1091)
at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1397)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1370)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1358)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:603)
at com.google.android.rcs.service.provisioning.RcsSmsReceiver.a(SourceFile:12)
at com.google.android.rcs.service.h.g(SourceFile:230)
at com.google.android.rcs.service.h.<init>(SourceFile:212)
at com.google.android.rcs.service.service.a.<init>(SourceFile:13)
at com.google.android.rcs.service.e.a(SourceFile:32)
at com.google.android.rcs.service.service.JibeService.d(SourceFile:145)
at com.google.android.rcs.service.service.JibeService.onCreate(SourceFile:91)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3404)
at android.app.ActivityThread.-wrap4(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1683)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Look here in Google Maps example
https://developers.google.com/maps/documentation/android-api/marker
If you want to add marker when clicking you can also look here:
http://wptrafficanalyzer.in/blog/adding-marker-on-touched-location-of-google-maps-using-android-api-v2-with-supportmapfragment/
The concept is to do like the folowing code:
// Setting a click event handler for the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
});
//Show Marker on a Location
googleMap.addMarker(new MarkerOptions().position(TIMES_SQUARE));
//Change Default Color of Marker
googleMap.addMarker(new MarkerOptions()
.position(BROOKLYN_BRIDGE)
.title("First Pit Stop")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
//Replace Default Marker Icon with Custom Image
googleMap.addMarker(new MarkerOptions()
.position(WALL_STREET)
.title("Wrong Turn!")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.my_flag)));
Get the users current position latitude and longitude
LatLng latLng = new LatLng(lat, lng);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
mMap.clear();
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
markerOptions.getPosition();
mCurrLocationMarker = mMap.addMarker(markerOptions);
try in this way.
Pass your latitude and longitude values
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
// adding marker
googleMap.addMarker(marker);
This code in MapsActivity works for me :
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
public void centreMapOnLocation(Location location, String title){
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,12));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centreMapOnLocation(lastKnownLocation,"Your Location");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
// 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.setOnMapLongClickListener(this);
Intent intent = getIntent();
if (intent.getIntExtra("Place Number",0) == 0 ){
// Zoom into users location
locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
centreMapOnLocation(location,"Your Location");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centreMapOnLocation(lastKnownLocation,"Your Location");
} else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
} else {
Location placeLocation = new Location(LocationManager.GPS_PROVIDER);
placeLocation.setLatitude(MainActivity.location.get(intent.getIntExtra("Place Number",0)).latitude);
placeLocation.setLongitude(MainActivity.location.get(intent.getIntExtra("Place Number",0)).longitude);
centreMapOnLocation(placeLocation,MainActivity.places.get(intent.getIntExtra("Place Number",0)));
}
}
#Override
public void onMapLongClick(LatLng latLng) {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
String adress ="";
try {
List<Address> listaddress = geocoder.getFromLocation(latLng.latitude,latLng.longitude,1);
if (listaddress != null && listaddress.size()>0){
if (listaddress.get(0).getThoroughfare() != null){
if (listaddress.get(0).getSubThoroughfare() != null){
adress += listaddress.get(0).getSubThoroughfare() + "";
}
adress += listaddress.get(0).getThoroughfare();
}
}
}catch (Exception e){
e.printStackTrace();
}
mMap.addMarker(new MarkerOptions().position(latLng).title(adress));
MainActivity.places.add(adress);
MainActivity.location.add(latLng);
MainActivity.arrayAdapter.notifyDataSetChanged();
Toast.makeText(this, "Location Saved..!", Toast.LENGTH_SHORT).show();
}
}
I have a google maps activity with a map an edittext and a button.
The screenshot of the activity that I have ready at the moment.
Whenever this activity is opened a marker is added to the map.
What I want further in this is that whenever the user inputs an address in that edittext and clicks the button, then another marker is added on the same map without erasing the previous marker and a polyline is created in the map joining the two markers.
I have tried adding the second marker but the app just crashes and I am not able to do that. It would be a great help if you guys can help me in adding the second marker.
Here is the activity code :
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private EditText findRouteEdittext;
private Button findRouteButton;
#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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
Intent intent = getIntent();
Geocoder coder = new Geocoder(this);
List<Address> addressList;
LatLng coord = null;
String completeAddress = intent.getStringExtra("completeAddress");
try {
addressList = coder.getFromLocationName(completeAddress, 5);
if (addressList != null) {
Address location = addressList.get(0);
coord = new LatLng(location.getLatitude(), location.getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
mMap = googleMap;
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(coord);
mMarkerOptions.title(completeAddress);
mMap.addMarker(mMarkerOptions).showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(coord));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coord, 14.0f));
}
}
EDIT 1
I finally got the answer myself, on where to add, it was basically a minor error but just so other people know where to add I will update the answer here :
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private EditText findRouteEdittext;
private Button findRouteButton;
#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);
findRouteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchString = findRouteEdittext.getText().toString().toLowerCase().trim();
if (searchString.equals("")){
// findRouteEditTextInputLayout.setErrorEnabled(true);
// findRouteEditTextInputLayout.setError("Enter a location or City!");
//use snackbar to show something.
}
else{
coder2 = new Geocoder(MapsActivity.this);
coord2 = null;
try {
addressList2 = coder2.getFromLocationName(searchString, 5);
if (addressList2 != null) {
Address location = addressList2.get(0);
coord2 = new LatLng(location.getLatitude(), location.getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (coord2!=null && coord!=null) {
mMap.clear();
mMarkerOptions2 = new MarkerOptions();
mMarkerOptions2.position(coord2);
mMarkerOptions2.title(searchString); //this is the address of the new string entered by the user
mMap.addMarker(mMarkerOptions2).showInfoWindow();
mMarkerOptions3 = new MarkerOptions();
mMarkerOptions3.position(coord);
mMarkerOptions3.title(completeAddress); //this is the address of the original string received from intent
mMap.addMarker(mMarkerOptions3).showInfoWindow();
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
Intent intent = getIntent();
Geocoder coder = new Geocoder(this);
List<Address> addressList;
LatLng coord = null;
String completeAddress = intent.getStringExtra("completeAddress");
try {
addressList = coder.getFromLocationName(completeAddress, 5);
if (addressList != null) {
Address location = addressList.get(0);
coord = new LatLng(location.getLatitude(), location.getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
mMap = googleMap;
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(coord);
mMarkerOptions.title(completeAddress);
mMap.addMarker(mMarkerOptions).showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(coord));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coord, 14.0f));
}
}
If you already got Location object then use below code to add new marker in to map.
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
place this code in side add button on click listener.
I have an an activity where the main view is Google maps. And I set up a marker when the map is initially loaded, but when I click on it I am not able to get the locality or anything. The maps appears, but I can't click on the marker, or tap or tap on the screen and hold to create a new marker. basically it cannot do anything...And i can't figure out why! Hope you guys can see something that I am not seeing.
Here is my main activity.
public class MapsActivity extends FragmentActivity {
//Maps
private GoogleMap mMap;
//Marker
private Marker marker;
//Location
private LocationListener locationListener = null;
private LocationManager locationManager = null;
private static final float DEFAULTZOOM = 15;
private double longitude_mapsActivity;
private double latitude_from_mapsActivity;
private String cityName_mapsActivity;
private String countryName_mapsActivity;
//ProgressBar
private ProgressBar myPB_MAPS;
//Buttons
private ImageButton fab_doneButton;
//SearchEditText
private EditText editText_Search;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
}
});
//Get user current location.
//myPB_MAPS = (ProgressBar) findViewById(R.id.myPB_MAPS);
//initialize your map
initMap();
//FAB button
fab_doneButton = (ImageButton) findViewById(R.id.activity_maps_FAB_done);
fab_doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (countryName_mapsActivity == null) {
Toast.makeText(MapsActivity.this, "Location is null", Toast.LENGTH_SHORT).show();
} else {
Global_Class.getInstance().getValue().countryName_GLOBAL = countryName_mapsActivity;
Global_Class.getInstance().getValue().cityName_GLOBAL = cityName_mapsActivity;
Global_Class.getInstance().getValue().longitude_user_GLOBAL = longitude_mapsActivity;
Global_Class.getInstance().getValue().latitude_user_GLOBAL = latitude_from_mapsActivity;
//Go to make sure we're sending all the GPS info, so we set geoLocationFromMapsIsPresent to true.
FinishCard.geoLocationFromMapsIsPresent();
FinishCard.setComingBackFromMaps();
Intent FinishCardIntent = new Intent(MapsActivity.this, FinishCard.class);
startActivity(FinishCardIntent);
}
}
});
//EditText
editText_Search = (EditText) findViewById(R.id.maps_EditText);
editText_Search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
}
});
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
}
private void performSearch()
{
String location = editText_Search.getText().toString();
if(location.length() == 0)
{
Toast.makeText(this,"Please enter a location",Toast.LENGTH_SHORT).show();
return;
}
//1-first step
Geocoder gc = new Geocoder(this);
List<Address> list = null;//For this function I only want a single address.
try
{
//3-Third step
list = gc.getFromLocationName(location,10);
}
catch (IOException e)
{
e.printStackTrace();
}
//4-Fourth step
Address add = list.get(0);//Give me the first and only item of the list.
//5-fifth step
String locality = add.getLocality();//So if you enter Taj mahal you get Agra, the place where its at, thats what Address locality does.
double lat = add.getLatitude();
double lng = add.getLongitude();
//GoToLocation() method
gotoLocation(lat, lng, DEFAULTZOOM);
//For Removing existing markers.
if(marker != null)
{
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(locality)
.position(new LatLng(lat, lng))
.draggable(true);
marker = mMap.addMarker(options);
}
private void gotoLocation(double lat, double lng, float zoom)
{
LatLng ll = new LatLng(lat,lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
private void setMarker(String locality, String country, double lat, double lng)
{
if(marker != null)
{
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(locality)
.position(new LatLng(lat, lng))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
.draggable(true);
if(country.length() > 0)
{
options.snippet(country);//Background highlight TEXT SUPER IMPORTANT
}
//.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
marker = mMap.addMarker(options);//So here we connect our marker to our map, which is used in initMap.
}
private void initMap()
{
if(mMap == null)
{
if(mMap != null)
{
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener()
{
#Override
public void onMapLongClick(LatLng ll) {
Geocoder gc = new Geocoder(MapsActivity.this);
List<Address> list = null;
try {
list = gc.getFromLocation(ll.latitude, ll.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address add = list.get(0);
MapsActivity.this.setMarker(add.getLocality(), add.getCountryName(), ll.latitude, ll.longitude);//this is where we set the orange marker.
latitude_from_mapsActivity= ll.latitude;
longitude_mapsActivity= ll.longitude;
countryName_mapsActivity = add.getCountryName();
cityName_mapsActivity = add.getLocality();
}
});
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker)
{
LatLng ll = marker.getPosition();
latitude_from_mapsActivity= ll.latitude;
longitude_mapsActivity = ll.longitude;
Geocoder gc = new Geocoder(MapsActivity.this);
//Global_Class.getInstance().getValue().cardLocality = "Paris";
List<Address> list = null;
try
{
list = gc.getFromLocation(ll.latitude, ll.longitude,1);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
Address add = list.get(0);
countryName_mapsActivity = add.getCountryName();
cityName_mapsActivity = add.getLocality();
return false;
}
catch (IndexOutOfBoundsException e)
{
return false;
}
}
});
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() //If you want to drag the original google maps marker you use this method, if you comment this out it will use the orange one.
{
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
Geocoder gc = new Geocoder(MapsActivity.this);
List<Address> list = null;
LatLng ll = marker.getPosition();
try {
list = gc.getFromLocation(ll.latitude, ll.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address add = list.get(0);
marker.setTitle(add.getLocality());
marker.setSnippet(add.getCountryName());
//marker.showInfoWindow();
}
});
}
}
}
}
Here is my xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.daprlabs.swipedeck.GeoLocation.MapsActivity">
<RelativeLayout
android:layout_width="340dp"
android:layout_height="50dp"
android:background="#FFFFFF"
android:elevation="10sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp">
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/maps_EditText"
android:imeOptions="actionSearch"
android:inputType="text"/>
</RelativeLayout>
<ProgressBar
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/myPB_MAPS"
android:layout_marginLeft="150dp"
android:layout_marginTop="55dp"/>
<ImageButton
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/circle_fab"
android:id="#+id/activity_maps_FAB_done"
android:layout_gravity="right|bottom"
android:src="#drawable/white_plus" />
</fragment>
You are contradicting yourself in your initMap().
Remove the following if statement:
if (mMap == null)
Also only call initMap() after mapFragment.getMapAsync returns. At this point, you know your map is ready to go.
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
initMap();
}
});
You are supposed to implement
OnMapReadyCallback
And in turn override
onMapReady
Now you can manipulate the Map within onMapReady. Before that, it is not certain that your Map has actually set properly.
Anything that manipulates the Map like loading markers over it and setting marker click listeners has to happen in onMapReady.
As an example of Map's manipulation at appropriate time, you can take hint from the following code where Map's camera is only set when it has properly set.
public class YourMapFragment extends Fragment implements OnMapReadyCallback {
...
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition,16));
mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + lat + "Lng:" + log));
}
...
}
I am developing an android google map application, that is showing current location on map starting.
I have an search bar in the application, when user enter any area name, then the second marker will be placed on that location.
Now my problem is, how to get second marker longitude and latitude position and make a route between the two markers.
my MainActivity.java code as follows:
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
private 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) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(27.746974, 85.301582);
mMap.addMarker(new MarkerOptions().position(sydney).title("Kathmandu, Nepal"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
// Enable MyLocation Button in the Map
mMap.setMyLocationEnabled(true);
}
}
Please Help me.
In your program you have used the code to get the LatLng of the second marker.
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
To make a polyline, refer to this link. By the this question has already been answered.
https://www.simplifiedcoding.net/google-maps-distance-calculator-google-maps-api/
Set Google Places API for search EdiText. Get the value from that and pass it as address..
Here is the code(address denoting strAddress here)
List<Address> address = null;
Geocoder coder = new Geocoder(getApplicationContext());
try {
address = coder.getFromLocationName(strAddress, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (address != null) {
Address location = address.get(0);
double lat = location.getLatitude();
double log = location.getLongitude();
}