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.
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 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;
}
}
}
I know that if I use this, I can get my location, but how can I get it automatically or by clicking a button; How can I update my location?
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(this.getLocation(), 16));
MarkerOptions a = new MarkerOptions().position(this.getLocation());
m = mMap.addMarker(a);
}
private LatLng getLocation() {
LatLng location = null;
gps = new GPSTracker(MainActivity.this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
location = new LatLng(latitude, longitude);
return location;
} else {
gps.showSettingsAlert();
location = new LatLng(-23.036602, -13.183594);
return location;
}
}
The only way I could do this was by restarting the activity, but I think this is not the best solution.
I am developing an android application in this application i want to draw path line on map
As user move path is draw automatically i found the lat and long and its change every time
When location is changed so i want to draw line on map when every time location is changed
i tried this
public void onLocationChanged(Location location) {
String msg = "Location:" + location.getLatitude() + ","
+ location.getLongitude();
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
double new_lat = location.getLatitude();
double new_long = location.getLongitude();
drawTrack(new_lat, new_long, previous_lat, previous_long);
previous_lat = new_lat;
previous_long = new_long;
}
This is what I did:
public void onLocationChanged(Location location) {
prevLatitude = latitude;
prevLongitude = longitude;
latitude = location.getLatitude();
longitude = location.getLongitude();
latLng = new LatLng(latitude, longitude);
PolylineOptions pOptions = new PolylineOptions()
.width(5)
.color(Color.GREEN)
.geodesic(true);
for (int z = 0; z < routePoints.size(); z++) {
LatLng point = routePoints.get(z);
pOptions.add(point);
}
line = googleMap.addPolyline(pOptions);
routePoints.add(latLng);
}
in which routePoints is an arraylist of LatLng's, line is your Polyline and googleMap is, ofcourse, your GoogleMap. So on the beginning of the class add:
private GoogleMap googleMap;
private Polyline line;
private ArrayList<LatLng> routePoints;
and in the onCreate add:
routePoints = new ArrayList<LatLng>();
hope this helps for you!:)
I am having trouble using the loactionListener in eclipse for android. I have been googling for a while now an I can't seem to see why this shouldn't work. The only thing I can think of is that maybe it is because my testing device has no sim. (the internet is provided via wifi).
I have used this as a reference and still, nothing.
Could anyone help me with this problem.
here is the relevant parts of my activity:
public class MainMenu extends Activity implements LocationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
theMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locMan = (LocationManager)getSystemService(LOCATION_SERVICE);
}
#Override
public void onLocationChanged(Location location) {
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
String title = getString(new StringLang().textSet(userLang,"marker_title"));
String snippit = getString(new StringLang().textSet(userLang,"marker_snip"));
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.snippet(snippit));
reverseGeoCode(lat, lng);
}
}
I was using a different method to display my location on the map, which worked well but it never updated. It always showed my location at the last place I used the GPS, which turns out was 60mile accross the country. I can see this is working but is there a better way of doing this.
Old method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
if(findViewById(R.id.the_map) != null){
//map has loaded continue
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
theMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
android.location.Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
LatLng lastLatLng ;
if(lastLoc == null){
/* Use the LocationManager class to obtain GPS locations */
double latitude = 0;
double longitude = 0;
lastLatLng = new LatLng(latitude, longitude);
lat = latitude;
lng = longitude;
String title = getString(new StringLang().textSet(userLang,"marker_title"));
String snippit = getString(new StringLang().textSet(userLang,"marker_snip"));
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.your_loc_icon))
.snippet(snippit));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(lastLatLng) // Sets the center of the map to user position
.zoom(0) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(20) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
currentLoc = lastLatLng;
theMap.animateCamera (CameraUpdateFactory.newCameraPosition(cameraPosition), 3000, null);
final TextView geoTagText = (TextView)findViewById(R.id.text_geoTag);
geoTagText.setText("We cannot find your current location, please check your settings.");
}else{
double latitude = lastLoc.getLatitude();
double longitude = lastLoc.getLongitude();
lastLatLng = new LatLng(latitude, longitude);
lat = latitude;
lng = longitude;
animateMap(lastLatLng);
}
}else{
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
theMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
android.location.Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
LatLng lastLatLng;
double latitude = lastLoc.getLatitude();
double longitude = lastLoc.getLongitude();
lastLatLng = new LatLng(latitude, longitude);
lat = latitude;
lng = longitude;
animateMap(lastLatLng);
//no map to load
}
}
#Override
public void onLocationChanged(Location location) {
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
String title = getString(new StringLang().textSet(userLang,"marker_title"));
String snippit = getString(new StringLang().textSet(userLang,"marker_snip"));
if(userMarker!=null) userMarker.remove();
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title(title)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.snippet(snippit));
}
it would also be useful to add that there is button to relocate the user manually if they want.
reLocBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
if(menuActive == true){
playSound();
LocationManager loc = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
android.location.Location gpsLoc = (Location) loc.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double lat = gpsLoc.getLatitude();
double lng = gpsLoc.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
animateMap(lastLatLng);
}
}
});
I'm not to sure why either method doesn't update, but the second method seams to work better on first load.
You don't appear to be using requestLocationUpdates() anywhere. In that method you pass a LocationListener object that it then calls for location updates.
i.e. in your case:
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
If you are using Google Maps API v2, you can do it using that, for example:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if(mMap != null){
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
and then set the listener for the map:
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
This will get called when the map first finds the location.
No need for LocationService or LocationManager at all.