2

I want to implement a google map inside of my app and I'm trying to convert a String into lat and long, something like "USA New York -> 2345.423423". I've searched on the internet and I've found a lot of examples to convert lat and long into String, but I don't understand why, because I don't even know the lat and long of the address where I live... I've found something and it works, but it converts into a List of addresses. I want something easier if it is possible. Thank you and Have a nice day

package com.currencymeeting.activities;

import java.io.IOException;
import java.util.List;

import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

 public class GoogleMapsActivity extends FragmentActivity{

GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_google_maps);

    SupportMapFragment supportMapFragment = (SupportMapFragment)
            getSupportFragmentManager().findFragmentById(R.id.googleMap);

    googleMap = supportMapFragment.getMap();

    new GeocoderTask().execute("USA New York");

}

private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{

    @Override
    protected List<Address> doInBackground(String... locationName) {
        // Creating an instance of Geocoder class
        Geocoder geocoder = new Geocoder(getBaseContext());
        List<Address> addresses = null;

        try {
            // Getting a maximum of 3 Address that matches the input text
            addresses = geocoder.getFromLocationName(locationName[0], 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return addresses;
    }

    @Override
    protected void onPostExecute(List<Address> addresses) {

        if(addresses==null || addresses.size()==0){
            Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
        }

        // Clears all the existing markers on the map
        googleMap.clear();

        // Adding Markers on Google Map for each matching address
        for(int i=0;i<addresses.size();i++){

            Address address = (Address) addresses.get(i);

            // Creating an instance of GeoPoint, to display in Google Map
            latLng = new LatLng(address.getLatitude(), address.getLongitude());

            String addressText = String.format("%s, %s",
            address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
            address.getCountryName());

            markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title(addressText);

            googleMap.addMarker(markerOptions);

            // Locate the first location
            if(i==0)
                googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
        }
    }
}

}

Mike
  • 279
  • 2
  • 11
  • 2
    So basically, you want us to edit someone else's code for your own purpose? – HavelTheGreat Feb 06 '15 at 19:48
  • As @Elizion is hinting at, this shouldn't take much modification to do what you want, it appears you haven't really tried much outside of copying over a tutorial. – zgc7009 Feb 06 '15 at 19:50
  • Oh my god.. I modifed it.. I want to make an Address from a String not from List<>... You're felling better if I delete those comments...? – Mike Feb 06 '15 at 19:56

2 Answers2

0

try this :

 Geocoder geocoder;
 List<Address> addresses;
 geocoder = new Geocoder(this, Locale.getDefault());
 addresses = geocoder.getFromLocation(latitude, longitude, 1);

 String address = addresses.get(0).getAddressLine(0);
 String city = addresses.get(0).getAddressLine(1);
 String country = addresses.get(0).getAddressLine(2);

also you can check this post out too

EDIT

  List<Address> getFromLocation (double latitude, double longitude, int maxResults)
  takes following paramters:
   latitude-    the latitude a point for the search
   longitude-   the longitude a point for the search
   maxResults-  max number of addresses to return.

so it will always return a List of address

Community
  • 1
  • 1
sujay
  • 681
  • 1
  • 8
  • 23
  • Thank you, I understand that there is no way to avoid the use of List
    .
    – Mike Feb 06 '15 at 20:06
  • if you are sure that only one address will be present in the entire list you can just return the first element of the list to the function you need and process it accordingly.. the third parameter in the getLocationFrom() function means that the function shall return maximum of 1 result, hence that result will be first element of your address list – sujay Feb 06 '15 at 20:11
0

For converting an address string into something else, consider using an address validation service API, such as the one provided by SmartyStreets.

For example, you are wanting the latitude and longitude for the city of New York. So feed the city and state into their demo, like this:

https://smartystreets.com/demo?city=new+york&state=ny

That returns a lot of information, but specifically it has the latitude and longitude for all of the ZIP Codes in New York City. If you were to specify a ZIP then it would return a more specific response.

If you hit their API directly with a request like this:

curl -v 'https://api.smartystreets.com/zipcode?auth-id=[your-auth-id]&
    auth-token=[your-auth-token]'
    --data-binary '[{"city":"New York","state":"NY","zipcode":"10001"}]'

You would get a JSON response like this:

[
    {
        "input_index": 0,
        "city_states": [
            {
                "city": "New York",
                "state_abbreviation": "NY",
                "state": "New York",
                "mailable_city": true
            }
        ],
        "zipcodes": [
            {
                "zipcode": "10001",
                "zipcode_type": "S",
                "county_fips": "36061",
                "county_name": "New York",
                "latitude": 40.74949,
                "longitude": -73.98935
            }
        ]
    }
]

A service like this could do the string to lat/lon conversion for you really easily. You would just need to read the data you want out of the JSON response.

SunSparc
  • 1,812
  • 2
  • 23
  • 47