I have included Google Map in my app and added 4 markers in the map by using a for loop. I also managed to get the zip code, the name of the city and the adress of these added markers by using Geocoder.
It all works, but the problem is that clicks on the markers do not always seem to work. Sometimes I have to make double taps to see the title of the markers. I really don't know why. Here is my full code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
String city, adress, zip;
Marker marker;
LatLngBounds.Builder builder = new LatLngBounds.Builder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng[] point_new = new LatLng[4];
point_new[0] = new LatLng(52.4788535, 13.32730760000004);
point_new[1] = new LatLng(52.4794297, 13.313520799999992);
point_new[2] = new LatLng(52.5272885, 13.458033200000045);
point_new[3] = new LatLng(52.52603999999999, 13.488159999999993);
for (int i = 0; i < point_new.length; i++) {
drawMarker(point_new[i]);
marker = mMap.addMarker(new MarkerOptions().position(point_new[i]));
mMap.moveCamera(CameraUpdateFactory.newLatLng(point_new[i]));
}
getAdress(52.4788535, 13.32730760000004 );
marker = mMap.addMarker(new MarkerOptions().position(point_new[0]).title(adress+"," + zip + "" + city));
getAdress(52.4794297, 13.313520799999992);
marker = mMap.addMarker(new MarkerOptions().position(point_new[1]).title(adress+"," + zip + "" + city));
getAdress(52.5272885, 13.458033200000045);
marker = mMap.addMarker(new MarkerOptions().position(point_new[2]).title(adress+"," + zip + "" + city));
getAdress(52.52603999999999, 13.488159999999993);
marker = mMap.addMarker(new MarkerOptions().position(point_new[3]).title(adress+"," + zip + "" + city));
for (int j = 0; j < point_new.length; j++) {
builder.include(point_new[j]);
}
LatLngBounds bounds = builder.build();
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 20));
}
public void drawMarker(LatLng point) {
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions.position(point);
// Adding marker on the Google Map
mMap.addMarker(markerOptions);
}
public void getAdress(double lat, double lng){
Geocoder geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(lat,lng,1);
} catch (IOException e) {
e.printStackTrace();
}
city = addresses.get(0).getLocality();
adress = addresses.get(0).getAddressLine(0);
zip = addresses.get(0).getPostalCode();
}
}
try this code, i have tested, its working
public class MapsActivity 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);
}
/**
* 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;
List<MarkerDesc> markerDescList = new ArrayList<>();
markerDescList.add(new MarkerDesc(new LatLng(52.4788535, 13.32730760000004), getAdress(52.4788535, 13.32730760000004)));
markerDescList.add(new MarkerDesc(new LatLng(52.4794297, 13.313520799999992), getAdress(52.4794297, 13.313520799999992)));
markerDescList.add(new MarkerDesc(new LatLng(52.5272885, 13.458033200000045), getAdress(52.5272885, 13.458033200000045)));
markerDescList.add(new MarkerDesc(new LatLng(52.52603999999999, 13.488159999999993), getAdress(52.52603999999999, 13.488159999999993)));
for(int i=0; i<markerDescList.size(); i++){
MarkerDesc markerDesc = markerDescList.get(i);
mMap.addMarker(new MarkerOptions()
.position(markerDesc.getLatLng())
.title(markerDesc.getAddresses().get(0).getLocality())
.snippet(markerDesc.getAddresses().get(0).getAddressLine(0)+"\n"+markerDesc.getAddresses().get(0).getPostalCode()+"\n"+markerDesc.getAddresses().get(0).getLocality())
.icon(BitmapDescriptorFactory.defaultMarker()));
}
LatLng latLng = markerDescList.get(markerDescList.size()-1).getLatLng();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder().target(latLng).zoom(15).bearing(0).tilt(25).build()));
}
public List<Address> getAdress(double lat, double lng){
Geocoder geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());
try {
return geocoder.getFromLocation(lat,lng,1);
} catch (IOException e) {
e.printStackTrace();
}
/*String city = addresses.get(0).getLocality();
String adress = addresses.get(0).getAddressLine(0);
String zip = addresses.get(0).getPostalCode();*/
return null;
}
private class MarkerDesc{
LatLng latLng;
List<Address> addresses;
private MarkerDesc(LatLng ltLng, List<Address> addr){
this.latLng=ltLng;
this.addresses = addr;
}
private LatLng getLatLng() {
return latLng;
}
private List<Address> getAddresses() {
return addresses;
}
}
}
Related
I am working on an app that gets the address of an event the user selects. The address is a String and is passed from one activity to a Google Map activity. I know the string arrives in the map activity as I have used a Toast to display it.
However, when I try to get the longitude and latitude of the address it doesn't work. The try catch block doesn't seem to execute unless I hard code and address into the addresses = geocoder.getFromLocationName('Dublin,Ireland', 1);
Any help would be greatly appreciated.
public class EventMapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private Intent MyTournamentsActivityIntent;
private String eventAddress = "";
double latitude = 0;
double longitude = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_map);
// 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);
MyTournamentsActivityIntent = getIntent();
eventAddress = MyTournamentsActivityIntent.getStringExtra("event_location");
Toast.makeText(getApplicationContext(),"Address from intent" + eventAddress,Toast.LENGTH_SHORT).show();
}//end onCreate
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Geocoder geocoder = new Geocoder(this);
List<Address> addresses;
try{
/*
This doesnt execute unless I hard code the eventAddress
*/
addresses = geocoder.getFromLocationName(eventAddress, 1);
latitude= addresses.get(0).getLatitude();
longitude= addresses.get(0).getLongitude();
Toast.makeText(getApplicationContext(),String.valueOf(latitude) + " " + String.valueOf(longitude) ,Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
e.printStackTrace();
}
LatLng eventLocation = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(eventLocation).title("Your Event"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(eventLocation));
}//end onMapReady
public void setEventAddress(String eventAddress) {
this.eventAddress = eventAddress;
}
}//end Class
Change this :
eventAddress = MyTournamentsActivityIntent.getStringExtra("event_location");
To this:
eventAddress = getIntent().getStringExtra("event_location");
And call mapFragment.getMapAsync(this);:
eventAddress = getIntent().getStringExtra("event_location");
mapFragment.getMapAsync(this);
After you get the eventAddress
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 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();
}
I am new in Android developing and location base applications in Google.
By tutorial of Google, i could show a single location.
After that i develop it more and read Double Latitude and Double Longitude from my DB.( By select with a where as you will see ! )
Now, i want to show all points(Latitude and Longitude)that exist in my DB.
I can read them from DB, but how can i show multi points(Latitude and Longitude) in my app.
Here is my code of MainActivity named LocationService :
public class LocationService extends FragmentActivity implements OnMapReadyCallback {
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_service);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
ConnectionHelper connectionHelper = new ConnectionHelper();
Statement statement;
try {
statement = connectionHelper.getMyConnection().createStatement();
ResultSet resultSet = statement.executeQuery("select Latitude, Longitude from myDB where Name='name'");
if(resultSet.next()) {
do {
latitude = Double.valueOf(resultSet.getString("Latitude"));
longitude = Double.valueOf(resultSet.getString("Longitude"));
LatLng myLocation = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(myLocation).title("Marker in Place!"));
map.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
} while (resultSet.next());
}
} catch (SQLException e) {
e.printStackTrace();
}
//
}
}
In onMapReady method i show a single point that is selected in my statement.
Now i want to get all points without where clause.(All Latitude and Longitude) and show them all.
I am looking for the best solution.
I will appreciate any help.
Best Regards !
You just need to create ArrayList<LatLag> and add one by one in that
List<LatLag> _list=new ArrayList<LatLng>();
if(resultSet.next()) {
do {
latitude = Double.valueOf(resultSet.getString("Latitude"));
longitude = Double.valueOf(resultSet.getString("Longitude"));
LatLng myLocation = new LatLng(latitude, longitude);
_list.add(myLocation );
} while (resultSet.next());
}
At last you got all the points in _list
Create a MapPoint class
public class MapPoint{
String name;
double long;
double lat;
public MapPoint(String name, double long, double lat){
this.name = name;
this.long = long;
this.lat = lat;
}
Then read your points from database to List<MapPoint> mList and do this in onMapReady
MapPoint[] mPoint;
mPoint = mList.toArray(new MapPoint[]{});
for (int i = 0; i < mPoint.length(); i++) {
double latitude = mPoint[i].lat();
double longitude = mPoint[i].long();
marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title(mPoint[i].name());
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
googleMap.addMarker(marker);
}
Hope it's help.
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);
}
}