How can I turn this method to be used in a fragment class? I am unable to use this method in a fragment (onCreate).
public void onSearch(View view) {
EditText location_tf = (EditText) findViewById(R.id.TFaddress);
String location = location_tf.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));
}
}
I do not know how the inclusion of an action through this method onSearch , the layout is ready to receive the method but do not know how to insert it in the class. I 'm trying to insert the onSearch method in this code :
public class FragmentC extends Fragment{
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.frag4, container,
false);
mMapView = (MapView) v.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroyView();
// Log.d(TAG, "onDestroyView");
Fragment f = getActivity()
.getSupportFragmentManager().findFragmentById(R.id.map);
if (f != null) {
getActivity().getSupportFragmentManager()
.beginTransaction().remove(f).commit();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
Assuming that mMapView is the same as mMap, and that theres a button that triggers the onSearch method, here's how your Fragment code should look like. Pay attention to the onCreateView changes and that the method onSearch does not recieves a View param:
private EditText mLocationEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.frag4, container,
false);
mMapView = (MapView) v.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
// Obtain the EditText view reference first
mLocationEditText = (EditText) v.findViewById(R.id.TFaddress);
// Obtain the button that triggers the onSearch reference
mButtonThatTriggersSearch = (Button) v..findViewById(R.id.search_button_id);
// Set the onClickListener that should excecute when someome clicks the button
mButtonThatTriggersSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
onSearch();
}
});
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
private void onSearch() {
String location = mLocationEditText.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(getActivity());
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mLocationEditText.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mLocationEditText.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
Related
i am new to android (2weeks old), i am having difficulties updating google map marker on fragment in pager viewer
After getting user longitude and latitude when photo is taken with camera from first fragment, i want to update marker or if possible recreate map with new marker on google map in second fragment.
After using interface to transfer data from fragment1(ImageFragment) to fragment2(MapFragment), i still cant update the map, i am having error on this line and anything relate to GoogleMap
googleMap.addMarker(marker);// null pointer exeception here
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));// and null pointer exeception here too
i still get nullpointer exception error on this line below. // adding marker googleMap.addMarker(marker); this is my logcat
Caused by: java.lang.NullPointerException at com.solexadex.itrak.i_trak.MapFragment.displayMapOnFragment(MapFragment.java:101)
These are my code: MapFragment Class
public class MapFragment extends Fragment implements ImageFragment.DisplayMapOnFragment {
//-------------- class variables
private MapView mMapView;
private GoogleMap mGoogleMap;
private GoogleMap googleMap;
private FragmentActivity myContext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_map, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 7.385044;
double longitude = 9.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
#Override
public void displayMapOnFragment(double latitude, double longitude) {
//initilizeMap();
// latitude and longitude
// double latitude = 9.155543;
//double longitude = 7.321151;//9.155543, 7.321151
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
//googleMap.
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}}
And ImageFragment Class below
public class ImageFragment extends Fragment {
private Context mContext;
double longitude, latitude;
public String street,city, state, country,zip,knownName,iDate;
private final Context dialogContext = getActivity();
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888;
FloatingActionButton button;
ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflater = getActivity().getLayoutInflater();
final View rootView = inflater.inflate(R.layout.fragment_image,
container, false);
mContext=getActivity().getApplicationContext();
button = ( FloatingActionButton) rootView.findViewById(R.id.fab);
imageView = (ImageView) rootView.findViewById(R.id.imageView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// now access the TextView as you want
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
// convert byte array to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
byteArray.length);
imageView.setImageBitmap(bitmap);
//call
this.getCoord();
}
}
}
public interface OnDataPass {
public void onDataPass(double uLat, double uLong);
}
public interface OnDataPass2 {
public void onDatapass2(String address, String city, String state, String postalCode, String KnowName, String createdDate);
}
public interface DisplayMapOnFragment {
public void displayMapOnFragment(double mapLat, double mapLong);
}
OnDataPass dataPasser;
OnDataPass2 dataPasser2;
DisplayMapOnFragment displayMapOnFragment;
#Override
public void onAttach(Activity a) {
super.onAttach(a);
try {
displayMapOnFragment = (DisplayMapOnFragment) a;
dataPasser = (OnDataPass) a;
dataPasser2 = (OnDataPass2) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString()
+ " must implement OnDataPass");
}
}
public void passData(double uLong, double uLat) {
dataPasser.onDataPass(uLong, uLat);
}
int aCount=20; //initialize counter to loop getCoord method if 0.0 is returned so as to ge value that is not 0.0
public void getCoord()
{
MapFragment mf = new MapFragment();
NewTrackActivity newTrackActivity=new NewTrackActivity();
TrackGPS gps = new TrackGPS(mContext);
if(gps.canGetLocation()){
longitude = gps.getLongitude();
latitude = gps.getLatitude();
if(aCount!=20)
Toast.makeText(mContext,"Retrying to get Coordinate: "+aCount+"\nLongitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude), Toast.LENGTH_LONG).show();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
//Log.e("latitude", "inside latitude--" + latitude);
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
street = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getLocality();
state = addresses.get(0).getAdminArea();
country = addresses.get(0).getCountryName();
zip = addresses.get(0).getPostalCode();
knownName = addresses.get(0).getFeatureName();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
iDate=dateFormat.format(date);
// locationTxt.setText(address + " " + city + " " + country);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
newTrackActivity.onDataPass( longitude, latitude);
newTrackActivity.onDatapass2( street, city, state, zip, knownName, iDate);
if(Double.compare(latitude,0.00)==0 && aCount>0) {
aCount--;
getCoord();
}
if(aCount<=1) {
Toast.makeText(mContext,"Please retake photo to get current position coordinate", Toast.LENGTH_LONG).show();
aCount=20; //reset count
}else
{
Toast.makeText(mContext,"Coordinates found", Toast.LENGTH_LONG).show();
}
newTrackActivity.displayMapOnFragment(latitude, longitude);
// Supply value
// Bundle args = new Bundle();
// args.putDouble("latitude", latitude);
//args.putDouble("longitude", longitude);
//mf.setArguments(args);
}
else
{
gps.showSettingsAlert(mContext);
}
}
}
Fragment_map.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
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 a newbie to the android and currently working on the Google-map API.
I am able to plot multiple markers on the map but want to join multiple markers with poly line.I have referred this for the directions concern but it is for two points only.
Below is the code for the Activity:
public class MainActivity extends AppCompatActivity {
// Google Map
private GoogleMap googleMap;
// latitude and longitude
double latitude;
double longitude;
String newtime;
ArrayList<LatLng> points;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
points = new ArrayList<LatLng>();
points.add(new LatLng(21.114369, 79.049423));
points.add(new LatLng(21.113913, 79.049203));
points.add(new LatLng(21.113478, 79.048736));
points.add(new LatLng(21.113002, 79.048592));
points.add(new LatLng(21.112857, 79.047315));
points.add(new LatLng(21.112997, 79.046741));
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.setMyLocationEnabled(true);
SimpleDateFormat sdfDateTime = new SimpleDateFormat("dd-MM-yy HH:mm:ss", Locale.US);
newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
// googleMap.addMarker(marker);
drawMarker(points);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
}
private void drawMarker(ArrayList<LatLng> l) {
// Creating an instance of MarkerOptions
for (int i = 0; i < l.size(); i++) {
latitude = l.get(i).latitude;
longitude = l.get(i).longitude;
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Bus")
.snippet(newtime);
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// Adding marker on the Google Map
googleMap.addMarker(marker);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(l.get(0).latitude, l.get(0).longitude)).zoom(18).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Please help/guide me to achieve the task.
~Thanks.
Modify your drawMarker() to the following:-
private void drawMarker(ArrayList<LatLng> l) {
// Creating an instance of MarkerOptions
PolylineOptions options = new PolylineOptions();
options.color(Color.RED);
for (int i = 0; i < l.size(); i++) {
options.add(l.get(i));
MarkerOptions marker = new MarkerOptions().position(l.get(i)).title("Bus")
.snippet(newtime);
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// Adding marker on the Google Map
googleMap.addMarker(marker);
}
googleMap.addPolyline(options);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(l.get(0).latitude, l.get(0).longitude)).zoom(18).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
Here it will add lines with red color, to change colors as your wish just modify the options.color().
I tried some code to make Geocoding reverse location (using Google Maps Android API v2) and show title with marker, but the marker title didn't showed when I run my application.
Here is my code :
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
googleMap = supportMapFragment.getMap();
// Setting a click event handler for the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
// Getting the Latitude and Longitude of the touched location
latLng = arg0;
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng);
}
});
}
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String>{
Context mContext;
public ReverseGeocodingTask(Context context){
super();
mContext = context;
}
// Finding address using reverse geocoding
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
String addressText="";
try {
addresses = geocoder.getFromLocation(latitude, longitude,1);
} catch (IOException e) {
e.printStackTrace();
}
if(addresses != null && addresses.size() > 0 ){
Address address = addresses.get(0);
addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
}
return addressText;
}
#Override
protected void onPostExecute(String addressText) {
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(addressText);
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
}
}
Is there a problem with my code ?
change your code in onPostExecute()
googleMap
.addMarker(
new MarkerOptions()
.position(loc)
.draggable(true)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title(addressText))
.showInfoWindow();
Try this
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
googleMap = supportMapFragment.getMap();
// Setting a click event handler for the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
// Getting the Latitude and Longitude of the touched location
latLng = arg0;
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
// Adding Marker on the touched location with address
new GetAddressTask().execute(latLng);
// new ReverseGeocodingTask(MainActivity.this).execute(latLng);
}
});
}
public class GetAddressTask extends AsyncTask<LatLng, Void, Integer>{
private LatLng loc;
String addressText;
#Override
protected Integer doInBackground(LatLng... params) {
int mFinalFlag=0;
loc=params[0];
String filterAddress = "";
Geocoder geoCoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(loc.latitude,
loc.longitude, 1);
if (addresses!=null&&addresses.size() > 0) {
Address address = addresses.get(0);
addressText = String.format(
"%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
}
} catch (IOException ex) {
} catch (Exception e2) {
e2.printStackTrace();
}
return mFinalFlag;
}
}
#Override
protected void onPostExecute(Integer result) {
googleMap.addMarker(
new MarkerOptions()
.position(loc)
.draggable(true)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title(addressText))
.showInfoWindow();
super.onPostExecute(result);
}
}