There was a question years ago, how to get lat long coordinates using only the adress ( here is the link to the question: How can I find the latitude and longitude from address? )
I understand the accepted answer there, but my problem is, for example, in Germany you have no unique adresses, so if I use only adresses to get lat and long coordinates, I may get wrong lat long coordinates. Like, there is one adress called "Hauptstrasse" which is in Berlin and in Frankfurt. So I will get wrong coordinates.
Is there any way to use Adress AND Zip code to get the right lat long coordinates ?
This code for example only uses adresses:
public GeoPoint getLocationFromAddress(String strAddress){
Geocoder coder = new Geocoder(this);
List<Address> address;
GeoPoint p1 = null;
try {
address = coder.getFromLocationName(strAddress,5);
if (address==null) {
return null;
}
Address location=address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new GeoPoint((double) (location.getLatitude() * 1E6),
(double) (location.getLongitude() * 1E6));
return p1;
}
}
I had the same problem.
This is how I solved this problem.
I have a txt file that contains adresses, zip codes and city names.
To keep your example for Germany: Hauptstrasse 123, 10978, Germany (this will be somewhere in Berlin)
Then, I put this txt file into assets folder and used a BufferedReader and created an Array.
public void readFile(){
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("YOURFILE")));
String line;
while ((line = reader.readLine()) != null) {
String splittedLine [] = line.split(",");
int numberofElements =2;
String[] onlyAdressandZip = Arrays.copyOf(splittedLine, numberofElements);
} catch (IOException e) {
e.printStackTrace();
}
As you can see, I did not use the name of the country (Germany) that's why I used Arrays.copyOf
Hauptstrasse 123, 10978 , Germany has a length of 3 but we only need Hauptstrasse 123 and 10978 that explains int numberofElements =2
That's it and then you can give onlyAdressandZip[0] and onlyAdressandZip[1] as input for the GeoCoder to get the right lat and long coordinates.
Related
I am developing a bus tracking application where I am getting the location using service from server. Now, with that I want to show the bus movement and draw a proper polyline. I achieved a part of this but facing two main issues:
Every time bus marker is showing, it is not getting removed. So, the older footprint of the bus is still present. Although I reached destination, I am seeing many bus icons.
I am able to draw the polyline by joining the latitude and longitude but it is showing sometimes a straight line.
I have attached two screenshots for that.
The code which I used is here:
private void setmMap() {
progressDialog.show();
if (broadcastReceiver == null)
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Testing", "inside the setmap");
// show progress dialog
try {
double latitude = intent.getDoubleExtra("lat", 22.560214);
double longitude = intent.getDoubleExtra("longi", 22.560214);
Log.d("SetMap", intent.getExtras().getString("time"));
LatLng startLocation = new LatLng(latitude, longitude);
m.setPosition(startLocation);
points.add(startLocation);
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int i = 0; i < points.size(); i++) {
LatLng point = points.get(i);
options.add(point);
}
line = mMap.addPolyline(options); //add Polyline
mMap.moveCamera(CameraUpdateFactory.newLatLng(startLocation));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(startLocation, 15));
progressDialog.cancel();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(context, Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String strLoc = "Latitude:: "+latitude+" ::Longitude:: "+longitude+" ::Address:: "+address+" "+city+" "+
state;
Toast.makeText(getApplicationContext(),strLoc, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
progressDialog.cancel();
}
}
};
registerReceiver(broadcastReceiver, new IntentFilter("carLocationService"));
}
Thanks,
Arindam.
1) you din't show part of code where marker m added, possible that code runs several times;
2) seems bus location sensor's polling period is quite large and does not allow tracking bus turns (bus can make several turns between it's known locations). So you need to interpolate path between known bus locations for example with Google Directions API.
This is my code
It don't have any error but
It shows in textView "No Address returned!"
double lat = 18.520430300000000000, log = 73.856743699999920000;
String address = null;
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
StringBuilder sb = null;
try {
List<Address> addresses = geocoder.getFromLocation(lat, log, 1);
sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)+ ",");
txtAdd.setText("Address :"+sb);
}
else{
txtAdd.setText("No Address returned!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
/*e.printStackTrace();*/
txtAdd.setText("Canont get Address!");
}
Plz give me solution on this
Thanks in Advance...
The doku gives one hint, maybe this should help
http://developer.android.com/reference/android/location/Geocoder.html
Returns an array of Addresses that are known to describe the area
immediately surrounding the given latitude and longitude. The returned
addresses will be localized for the locale provided to this class's
constructor.
The returned values may be obtained by means of a network lookup. The
results are a best guess and are not guaranteed to be meaningful or
correct. It may be useful to call this method from a thread separate
from your primary UI thread.
The Android API has Location.distanceBetween(), which accepts two lat/lon values and returns a distance in meters. Is there a way that I could get this distance with only having a zip (postal) code for one of my points?
You may want to use Android's Geocoder API. Something like this should work:
String locationName = zipCode + ", " + countryName;
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> address = geoCoder.getFromLocationName(locationName, 1);
double latitude = address.get(0).getLatitude();
double longitude = address.get(0).getLongitude();
Location.distanceBetween(...);
} catch (IOException e) {
e.printStackTrace();
}
You need to include the country's name because of this: Get latitude and longitude based on zip using Geocoder class in Android
Is there any way to get zip-code of the current user location from location or lat or long.
If so how?
Use Android Geocoder API!
getFromLocation(double, double, int) is all you need.
Yes you can...All you need to do is extract the
http://maps.google.com/maps/geo?ll=latitude,longitude
http://maps.google.com/maps/geo?ll=10.345561,123.896932
Or try experimenting this solutions.I can give you an idea.
You can have a city right? WIth this json data, If you have a database(at maxmind.com) of the zipcode with this format
CountryCode | City | ZipCode
PH |Cebu |6000
Now query your database that is relative to the countrycode that googles return.
UPDATE
The Geocoding API v2 has been turned down on September 9th, 2013.
Here's the new URL of API service
http://maps.googleapis.com/maps/api/geocode/json?latlng=your_latitude,your_longitude
http://maps.googleapis.com/maps/api/geocode/json?latlng=10.32,123.90&sensor=true
Geocoder based implementation:
private String getZipCodeFromLocation(Location location) {
Address addr = getAddressFromLocation(location);
return addr.getPostalCode() == null ? "" : addr.getPostalCode();
}
private Address getAddressFromLocation(Location location) {
Geocoder geocoder = new Geocoder(this);
Address address = new Address(Locale.getDefault());
try {
List<Address> addr = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addr.size() > 0) {
address = addr.get(0);
}
} catch (IOException e) {
e.printStackTrace();
}
return address;
}
You can get also other information from address, for example city name.
I'm trying to get the street name of my current location but I can't seem to get it.
I use this method to retrieve the Address:
public Address getAddressForLocation(Context context, Location location) throws IOException {
if (location == null) {
return null;
}
double latitude = location.getLatitude();
double longitude = location.getLongitude();
int maxResults = 1;
Geocoder gc = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gc.getFromLocation(latitude, longitude, maxResults);
if (addresses.size() == 1) {
return addresses.get(0);
} else {
return null;
}
}
And then I can do things like. address.getLocality() and address.getPostalCode()
But what I want is the street name. Like in "Potterstreet 12". When I print the AddressLine(0) and AddressLine(1) I only get the postalcode, city and country.
How can I retrieve the street name of the position i'm currently at?
Have you tried using getAddressLine ?
See here for more info on this method
Something like this should do (untested):
for (int i = 0; i < addresses.getMaxAddressLineIndex(); i++) {
Log.d("=Adress=",addresses.getAddressLine(i));
}
Try something like this in your code
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(), location
.getLongitude(), 1);
if (addresses.size() > 0)
StreetName=addresses.get(0).getThoroughfare();
String s = longitude+"\n"+latitude +
"\n\nMy Currrent Street is: "+StreetName;
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
it works for me :-) Good luck ;-)
If you have a complete address (city + street), in
address.getAddressLine(0)
you find the street name and number.
getFromLocation wasn't working for me either. There are a couple steps you can take.
1. First off go into gradle and make sure you are using the latest play services lib.
2. Don't over specify, the reason I got no results is because I had to much info in my address. When I removed the postal code I got results every time.
3. Try the online api:
http://maps.google.com/maps/api/geocode/json?address=192%20McEwan%20Dr%20E,%20Caledon,%20ON&sensor=false
Just replace the address in there with yours.
Good luck
I had a very similar problem but with the Country name, this is the function I ended up using:
function getCountry(results) {
var geocoderAddressComponent,addressComponentTypes,address;
for (var i in results) {
geocoderAddressComponent = results[i].address_components;
for (var j in geocoderAddressComponent) {
address = geocoderAddressComponent[j];
addressComponentTypes = geocoderAddressComponent[j].types;
for (var k in addressComponentTypes) {
if (addressComponentTypes[k] == 'country') {
return address.long_name;
}
}
}
}
return 'Unknown';
}
You should be able to adapt this to get the street name out without much fuss.
Inspired by this answer
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses =
gcd.getFromLocation(currentLatitude, currentLongitude,100);
if (addresses.size() > 0 && addresses != null) {
StringBuilder result = new StringBuilder();
myaddress.setText(addresses.get(0).getFeatureName()+"-"+addresses.get(0).getLocality()+"-"+addresses.get(0).getAdminArea()+"-"+addresses.get(0).getCountryName());
}
getfeaturename() return Streetname
getlocality() return city
getadminarea() return State
That's All..!