Skip to content

Instantly share code, notes, and snippets.

@Bracktus
Created November 3, 2020 13:11
Show Gist options
  • Save Bracktus/4d3b66019eda544fd285aba4cbc613e5 to your computer and use it in GitHub Desktop.
Save Bracktus/4d3b66019eda544fd285aba4cbc613e5 to your computer and use it in GitHub Desktop.
Address to Lat/Long
package com.example.locationfromaddress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Pair;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public String convertPostcodeToAddress(String postcode, Context context) throws IOException {
Geocoder coder = new Geocoder(context);
List<Address> address;
String fin;
try {
address = coder.getFromLocationName(postcode, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
String x = Double.toString(location.getLatitude());
String y = Double.toString(location.getLongitude());
fin = x + " " + y;
} catch (Exception ex) {
ex.printStackTrace();
fin = "no address found";
}
return fin;
}
public void sendMessage(View view) throws IOException {
EditText editText = (EditText)findViewById(R.id.editTextTextPersonName2);
String editTextStr = editText.getText().toString();
TextView tv1 = (TextView)findViewById(R.id.textView);
String addr = convertPostcodeToAddress(editTextStr, getBaseContext());
tv1.setText(addr);
}
}
@Bracktus
Copy link
Author

Bracktus commented Nov 3, 2020

editTextTextPersonName2 and textView are both defined in the xml
A button is wired to sendMessage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment