Search code examples
postal-code

How to get street name from postcode using maps API?


I'm looking for solution to change post code e.g DD3 7BN, but not using geo position. I found one solution using url http://maps.googleapis.com/maps/api/geocode/json?address=DD37bn. One guy was provide another solution but its not work for me.

But it shows error GRPS Failed. What is the best solution for my problem?

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getAddressByPostalCode("");
    }


    public void getAddressByPostalCode(String val_pcode) {

        Geocoder geocoder = new Geocoder(this.getApplicationContext(), Locale.getDefault());

        try {

            List<Address> addresses1 = geocoder.getFromLocationName (val_pcode, 1);

            Address obj1 = addresses1.get(0);

            List<Address> addresses = geocoder.getFromLocation(obj1.getLatitude(), obj1.getLongitude(), 1);
            Address obj = addresses.get(0);
            /*TextView street = (TextView)findViewById(R.id.editText1);
            TextView pcode = (TextView)findViewById(R.id.editText2);
            TextView blk = (TextView)findViewById(R.id.editText3);
            TextView build = (TextView)findViewById(R.id.editText4);

            street.setText(obj.getThoroughfare());
            pcode.setText(obj.getPostalCode());
            blk.setText(obj.getSubThoroughfare());
            build.setText(obj.getPremises());*/


        } catch (IOException e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
}

Solution

  • Be aware that UK postcodes don't always relate to single street, HD7 5UZ covers 7 and as a result google API doesn't return the "route" element - http://maps.googleapis.com/maps/api/geocode/json?address=HD75UZ

    I don't think there are any open datasets that offer the link between postcode and street, there are ones that have a complete list of streets or postcodes along with other geo data though.

    Another solution for the UK is to use an API that looks at the Royal Mail PAF dataset, this will have linkage between postcodes and the streets they relate to. This will come with a cost however typically if you are after only the street name, not premise level data the cost is quite low.

    An example would be the "street" endpoint from Allies Computing (who I work for) which will return an array of the streets. Which you can either get the user to select the right one or if there is only one, auto select it for them.

    Most other PAF resellers also offer a street level search and they can be found via the Powered by PAF website.