如何从我的应用程序中打开标准谷歌地图应用程序?

时间:2022-03-12 07:37:27

Once user presses button in my application, I would like to open standard Google Map application and to show particular location. How can I do it? (without using com.google.android.maps.MapView)

在我的应用程序中,一旦用户按下按钮,我就会打开标准的谷歌地图应用程序,并显示特定的位置。我怎么做呢?(没有使用com.google.android.maps.MapView)

7 个解决方案

#1


193  

You should create an Intent object with a geo-URI:

您应该创建一个带有地理uri的意图对象:

String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);

If you want to specify an address, you should use another form of geo-URI: geo:0,0?q=address.

如果您想指定一个地址,您应该使用另一种形式的地理uri: geo:0,0?q=address。

reference : https://developer.android.com/guide/components/intents-common.html#Maps

参考:https://developer.android.com/guide/components/intents-common.html地图

#2


75  

You can also simply use http://maps.google.com/maps as your URI

您也可以使用http://maps.google.com/maps作为您的URI

String uri = "http://maps.google.com/maps?saddr=" + sourceLatitude + "," + sourceLongitude + "&daddr=" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);

or you can make sure that the Google Maps app only is used, this stops the intent filter (dialog) from appearing, by using

或者您可以确保只使用谷歌地图应用程序,这将阻止意图过滤器(对话框)通过使用出现

intent.setPackage("com.google.android.apps.maps");

like so:

像这样:

String uri = "http://maps.google.com/maps?saddr=" + sourceLatitude + "," + sourceLongitude + "&daddr=" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

or you can add labels to the locations by adding a string inside parentheses after each set of coordinates like so:

或者你也可以在每一组坐标之后在括号中加入一个字符串,例如:

String uri = "http://maps.google.com/maps?saddr=" + sourceLatitude + "," + sourceLongitude + "(" + "Home Sweet Home" + ")&daddr=" + destinationLatitude + "," + destinationLongitude + " (" + "Where the party is at" + ")";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

To use the users current location as the starting point (unfortunately I haven't found a way to label the current location) then just drop off the saddr parameter as follows:

要使用用户当前位置作为起点(不幸的是,我还没有找到标记当前位置的方法),那么只需删除saddr参数如下所示:

String uri = "http://maps.google.com/maps?daddr=" + destinationLatitude + "," + destinationLongitude + " (" + "Where the party is at" + ")";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

For completeness, if the user doesn't have the maps app installed then it's going to be a good idea to catch the ActivityNotFoundException, as @TonyQ states, then we can start the activity again without the maps app restriction, we can be pretty sure that we will never get to the Toast at the end since an internet browser is a valid application to launch this url scheme too.

出于完整性的考虑,如果用户没有安装地图应用那么这将是一个好主意抓ActivityNotFoundException,@TonyQ州,然后我们可以再次启动活动没有地图应用的限制,我们可以非常肯定的是,我们永远不会到达末尾的吐司自互联网浏览器是一个有效的应用程序启动这个url方案。

        String uri = "http://maps.google.com/maps?daddr=" + 12f + "," + 2f + " (" + "Where the party is at" + ")";
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        intent.setPackage("com.google.android.apps.maps");
        try
        {
            startActivity(intent);
        }
        catch(ActivityNotFoundException ex)
        {
            try
            {
                Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                startActivity(unrestrictedIntent);
            }
            catch(ActivityNotFoundException innerEx)
            {
                Toast.makeText(this, "Please install a maps application", Toast.LENGTH_LONG).show();
            }
        }

EDIT:

编辑:

For directions, a navigation intent is now supported with google.navigation

对于方向,google.navigation支持导航意图

Uri navigationIntentUri = Uri.parse("google.navigation:q=" + 12f " +"," + 2f);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, navigationIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);

#3


37  

Using String format will help but you must be care full with the locale. In germany float will be separates with in comma instead an point.

使用字符串格式将会有所帮助,但是您必须完全关注语言环境。在德国,浮动将用逗号而不是点分开。

Using String.format("geo:%f,%f",5.1,2.1); on locale english the result will be "geo:5.1,2.1" but with locale german you will get "geo:5,1,2,1"

使用String.format(“geo:% f % f”,5.1,2.1);在语言环境英语中,结果将是“geo:5.1,2.1”,但是在语言环境德语中,您将得到“geo:5,1,2,1”

You should use the English locale to prevent this behavior.

您应该使用英语语言环境来防止这种行为。

String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);

To set an label to the geo point you can extend your geo uri by using:

要将标签设置为geo点,可以使用以下方法扩展geo uri:

!!! but be carefull with this the geo-uri is still under develoment http://tools.ietf.org/html/draft-mayrhofer-geo-uri-00

! ! !但是要注意的是,geo-uri仍然处于开发状态http://tools.ietf.org/html/draft-mayrhofer-geuri-00

String uri = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f (%s)", 
                           latitude, longitude, zoom, latitude, longitude, label);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);

#4


8  

Check this page from google :

查看谷歌中的这一页:

http://developer.android.com/guide/appendix/g-app-intents.html

http://developer.android.com/guide/appendix/g-app-intents.html

You can use a URI of the form

您可以使用表单的URI

geo:latitude,longitude

to open Google map viewer and point it to a location.

打开谷歌地图查看器并将其指向一个位置。

#5


6  

You can also use the code snippet below, with this manner the existence of google maps is checked before the intent is started.

您还可以使用下面的代码片段,以这种方式在启动意图之前检查谷歌映射的存在性。

Uri gmmIntentUri = Uri.parse(String.format(Locale.ENGLISH,"geo:%f,%f", latitude, longitude));
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(mapIntent);
}

Reference: https://developers.google.com/maps/documentation/android-api/intents

参考:https://developers.google.com/maps/documentation/android-api/intents

#6


5  

Sometimes if there's no any application associated with geo: protocal , you could use try-catch to get the ActivityNotFoundException to handle it.

有时,如果没有与geo: protocal相关的应用程序,您可以使用try-catch获得ActivityNotFoundException来处理它。

It happens when you use some emulator like androVM which is not installed google map by default.

当您使用android这样的仿真器时,会发生这种情况,默认情况下不会安装谷歌映射。

#7


0  

I have a sample app where I prepare the intent and just pass the CITY_NAME in the intent to the maps marker activity which eventually calculates longitude and latitude by Geocoder using CITY_NAME.

我有一个示例应用程序,我在这里准备意图,并将CITY_NAME传递给地图标记活动,该活动最终通过Geocoder使用CITY_NAME计算经度和纬度。

Below is the code snippet of starting the maps marker activity and the complete MapsMarkerActivity.

下面是启动映射标记活动和完整的MapsMarkerActivity的代码片段。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    } else if (id == R.id.action_refresh) {
        Log.d(APP_TAG, "onOptionsItemSelected Refresh selected");
        new MainActivityFragment.FetchWeatherTask().execute(CITY, FORECAS_DAYS);
        return true;
    } else if (id == R.id.action_map) {
        Log.d(APP_TAG, "onOptionsItemSelected Map selected");
        Intent intent = new Intent(this, MapsMarkerActivity.class);
        intent.putExtra("CITY_NAME", CITY);
        startActivity(intent);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public class MapsMarkerActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    private String cityName = "";

    private double longitude;

    private double latitude;

    static final int numberOptions = 10;

    String [] optionArray = new String[numberOptions];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_map);
        // Get the SupportMapFragment and request notification
        // when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        // Test whether geocoder is present on platform
        if(Geocoder.isPresent()){
            cityName = getIntent().getStringExtra("CITY_NAME");
            geocodeLocation(cityName);
        } else {
            String noGoGeo = "FAILURE: No Geocoder on this platform.";
            Toast.makeText(this, noGoGeo, Toast.LENGTH_LONG).show();
            return;
        }
    }

    /**
     * Manipulates the map when it's available.
     * The API invokes this callback 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 receives a prompt to install
     * Play services inside the SupportMapFragment. The API invokes this method after the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        // Add a marker in Sydney, Australia,
        // and move the map's camera to the same location.
        LatLng sydney = new LatLng(latitude, longitude);
        // If cityName is not available then use
        // Default Location.
        String markerDisplay = "Default Location";
        if (cityName != null
                && cityName.length() > 0) {
            markerDisplay = "Marker in " + cityName;
        }
        googleMap.addMarker(new MarkerOptions().position(sydney)
                .title(markerDisplay));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

    /**
     * Method to geocode location passed as string (e.g., "Pentagon"), which
     * places the corresponding latitude and longitude in the variables lat and lon.
     *
     * @param placeName
     */
    private void geocodeLocation(String placeName){

        // Following adapted from Conder and Darcey, pp.321 ff.
        Geocoder gcoder = new Geocoder(this);

        // Note that the Geocoder uses synchronous network access, so in a serious application
        // it would be best to put it on a background thread to prevent blocking the main UI if network
        // access is slow. Here we are just giving an example of how to use it so, for simplicity, we
        // don't put it on a separate thread.  See the class RouteMapper in this package for an example
        // of making a network access on a background thread. Geocoding is implemented by a backend
        // that is not part of the core Android framework, so we use the static method
        // Geocoder.isPresent() to test for presence of the required backend on the given platform.

        try{
            List<Address> results = null;
            if(Geocoder.isPresent()){
                results = gcoder.getFromLocationName(placeName, numberOptions);
            } else {
                Log.i(MainActivity.APP_TAG, "No Geocoder found");
                return;
            }
            Iterator<Address> locations = results.iterator();
            String raw = "\nRaw String:\n";
            String country;
            int opCount = 0;
            while(locations.hasNext()){
                Address location = locations.next();
                if(opCount == 0 && location != null){
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
                country = location.getCountryName();
                if(country == null) {
                    country = "";
                } else {
                    country =  ", " + country;
                }
                raw += location+"\n";
                optionArray[opCount] = location.getAddressLine(0)+", "
                        +location.getAddressLine(1)+country+"\n";
                opCount ++;
            }
            // Log the returned data
            Log.d(MainActivity.APP_TAG, raw);
            Log.d(MainActivity.APP_TAG, "\nOptions:\n");
            for(int i=0; i<opCount; i++){
                Log.i(MainActivity.APP_TAG, "("+(i+1)+") "+optionArray[i]);
            }
            Log.d(MainActivity.APP_TAG, "latitude=" + latitude + ";longitude=" + longitude);
        } catch (Exception e){
            Log.d(MainActivity.APP_TAG, "I/O Failure; do you have a network connection?",e);
        }
    }
}

Links expire so i have pasted complete code above but just in case if you would like to see complete code then its available at : https://github.com/gosaliajigar/CSC519/tree/master/CSC519_HW4_89753

链接过期,所以我粘贴了上面的完整代码,但是如果您想看到完整的代码,那么它的可用地址是:https://github.com/gosaliajigar/CSC519/tree/master/CSC519_HW4_89753

#1


193  

You should create an Intent object with a geo-URI:

您应该创建一个带有地理uri的意图对象:

String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);

If you want to specify an address, you should use another form of geo-URI: geo:0,0?q=address.

如果您想指定一个地址,您应该使用另一种形式的地理uri: geo:0,0?q=address。

reference : https://developer.android.com/guide/components/intents-common.html#Maps

参考:https://developer.android.com/guide/components/intents-common.html地图

#2


75  

You can also simply use http://maps.google.com/maps as your URI

您也可以使用http://maps.google.com/maps作为您的URI

String uri = "http://maps.google.com/maps?saddr=" + sourceLatitude + "," + sourceLongitude + "&daddr=" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);

or you can make sure that the Google Maps app only is used, this stops the intent filter (dialog) from appearing, by using

或者您可以确保只使用谷歌地图应用程序,这将阻止意图过滤器(对话框)通过使用出现

intent.setPackage("com.google.android.apps.maps");

like so:

像这样:

String uri = "http://maps.google.com/maps?saddr=" + sourceLatitude + "," + sourceLongitude + "&daddr=" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

or you can add labels to the locations by adding a string inside parentheses after each set of coordinates like so:

或者你也可以在每一组坐标之后在括号中加入一个字符串,例如:

String uri = "http://maps.google.com/maps?saddr=" + sourceLatitude + "," + sourceLongitude + "(" + "Home Sweet Home" + ")&daddr=" + destinationLatitude + "," + destinationLongitude + " (" + "Where the party is at" + ")";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

To use the users current location as the starting point (unfortunately I haven't found a way to label the current location) then just drop off the saddr parameter as follows:

要使用用户当前位置作为起点(不幸的是,我还没有找到标记当前位置的方法),那么只需删除saddr参数如下所示:

String uri = "http://maps.google.com/maps?daddr=" + destinationLatitude + "," + destinationLongitude + " (" + "Where the party is at" + ")";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

For completeness, if the user doesn't have the maps app installed then it's going to be a good idea to catch the ActivityNotFoundException, as @TonyQ states, then we can start the activity again without the maps app restriction, we can be pretty sure that we will never get to the Toast at the end since an internet browser is a valid application to launch this url scheme too.

出于完整性的考虑,如果用户没有安装地图应用那么这将是一个好主意抓ActivityNotFoundException,@TonyQ州,然后我们可以再次启动活动没有地图应用的限制,我们可以非常肯定的是,我们永远不会到达末尾的吐司自互联网浏览器是一个有效的应用程序启动这个url方案。

        String uri = "http://maps.google.com/maps?daddr=" + 12f + "," + 2f + " (" + "Where the party is at" + ")";
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        intent.setPackage("com.google.android.apps.maps");
        try
        {
            startActivity(intent);
        }
        catch(ActivityNotFoundException ex)
        {
            try
            {
                Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                startActivity(unrestrictedIntent);
            }
            catch(ActivityNotFoundException innerEx)
            {
                Toast.makeText(this, "Please install a maps application", Toast.LENGTH_LONG).show();
            }
        }

EDIT:

编辑:

For directions, a navigation intent is now supported with google.navigation

对于方向,google.navigation支持导航意图

Uri navigationIntentUri = Uri.parse("google.navigation:q=" + 12f " +"," + 2f);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, navigationIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);

#3


37  

Using String format will help but you must be care full with the locale. In germany float will be separates with in comma instead an point.

使用字符串格式将会有所帮助,但是您必须完全关注语言环境。在德国,浮动将用逗号而不是点分开。

Using String.format("geo:%f,%f",5.1,2.1); on locale english the result will be "geo:5.1,2.1" but with locale german you will get "geo:5,1,2,1"

使用String.format(“geo:% f % f”,5.1,2.1);在语言环境英语中,结果将是“geo:5.1,2.1”,但是在语言环境德语中,您将得到“geo:5,1,2,1”

You should use the English locale to prevent this behavior.

您应该使用英语语言环境来防止这种行为。

String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);

To set an label to the geo point you can extend your geo uri by using:

要将标签设置为geo点,可以使用以下方法扩展geo uri:

!!! but be carefull with this the geo-uri is still under develoment http://tools.ietf.org/html/draft-mayrhofer-geo-uri-00

! ! !但是要注意的是,geo-uri仍然处于开发状态http://tools.ietf.org/html/draft-mayrhofer-geuri-00

String uri = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f (%s)", 
                           latitude, longitude, zoom, latitude, longitude, label);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);

#4


8  

Check this page from google :

查看谷歌中的这一页:

http://developer.android.com/guide/appendix/g-app-intents.html

http://developer.android.com/guide/appendix/g-app-intents.html

You can use a URI of the form

您可以使用表单的URI

geo:latitude,longitude

to open Google map viewer and point it to a location.

打开谷歌地图查看器并将其指向一个位置。

#5


6  

You can also use the code snippet below, with this manner the existence of google maps is checked before the intent is started.

您还可以使用下面的代码片段,以这种方式在启动意图之前检查谷歌映射的存在性。

Uri gmmIntentUri = Uri.parse(String.format(Locale.ENGLISH,"geo:%f,%f", latitude, longitude));
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(mapIntent);
}

Reference: https://developers.google.com/maps/documentation/android-api/intents

参考:https://developers.google.com/maps/documentation/android-api/intents

#6


5  

Sometimes if there's no any application associated with geo: protocal , you could use try-catch to get the ActivityNotFoundException to handle it.

有时,如果没有与geo: protocal相关的应用程序,您可以使用try-catch获得ActivityNotFoundException来处理它。

It happens when you use some emulator like androVM which is not installed google map by default.

当您使用android这样的仿真器时,会发生这种情况,默认情况下不会安装谷歌映射。

#7


0  

I have a sample app where I prepare the intent and just pass the CITY_NAME in the intent to the maps marker activity which eventually calculates longitude and latitude by Geocoder using CITY_NAME.

我有一个示例应用程序,我在这里准备意图,并将CITY_NAME传递给地图标记活动,该活动最终通过Geocoder使用CITY_NAME计算经度和纬度。

Below is the code snippet of starting the maps marker activity and the complete MapsMarkerActivity.

下面是启动映射标记活动和完整的MapsMarkerActivity的代码片段。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    } else if (id == R.id.action_refresh) {
        Log.d(APP_TAG, "onOptionsItemSelected Refresh selected");
        new MainActivityFragment.FetchWeatherTask().execute(CITY, FORECAS_DAYS);
        return true;
    } else if (id == R.id.action_map) {
        Log.d(APP_TAG, "onOptionsItemSelected Map selected");
        Intent intent = new Intent(this, MapsMarkerActivity.class);
        intent.putExtra("CITY_NAME", CITY);
        startActivity(intent);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public class MapsMarkerActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    private String cityName = "";

    private double longitude;

    private double latitude;

    static final int numberOptions = 10;

    String [] optionArray = new String[numberOptions];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_map);
        // Get the SupportMapFragment and request notification
        // when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        // Test whether geocoder is present on platform
        if(Geocoder.isPresent()){
            cityName = getIntent().getStringExtra("CITY_NAME");
            geocodeLocation(cityName);
        } else {
            String noGoGeo = "FAILURE: No Geocoder on this platform.";
            Toast.makeText(this, noGoGeo, Toast.LENGTH_LONG).show();
            return;
        }
    }

    /**
     * Manipulates the map when it's available.
     * The API invokes this callback 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 receives a prompt to install
     * Play services inside the SupportMapFragment. The API invokes this method after the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        // Add a marker in Sydney, Australia,
        // and move the map's camera to the same location.
        LatLng sydney = new LatLng(latitude, longitude);
        // If cityName is not available then use
        // Default Location.
        String markerDisplay = "Default Location";
        if (cityName != null
                && cityName.length() > 0) {
            markerDisplay = "Marker in " + cityName;
        }
        googleMap.addMarker(new MarkerOptions().position(sydney)
                .title(markerDisplay));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

    /**
     * Method to geocode location passed as string (e.g., "Pentagon"), which
     * places the corresponding latitude and longitude in the variables lat and lon.
     *
     * @param placeName
     */
    private void geocodeLocation(String placeName){

        // Following adapted from Conder and Darcey, pp.321 ff.
        Geocoder gcoder = new Geocoder(this);

        // Note that the Geocoder uses synchronous network access, so in a serious application
        // it would be best to put it on a background thread to prevent blocking the main UI if network
        // access is slow. Here we are just giving an example of how to use it so, for simplicity, we
        // don't put it on a separate thread.  See the class RouteMapper in this package for an example
        // of making a network access on a background thread. Geocoding is implemented by a backend
        // that is not part of the core Android framework, so we use the static method
        // Geocoder.isPresent() to test for presence of the required backend on the given platform.

        try{
            List<Address> results = null;
            if(Geocoder.isPresent()){
                results = gcoder.getFromLocationName(placeName, numberOptions);
            } else {
                Log.i(MainActivity.APP_TAG, "No Geocoder found");
                return;
            }
            Iterator<Address> locations = results.iterator();
            String raw = "\nRaw String:\n";
            String country;
            int opCount = 0;
            while(locations.hasNext()){
                Address location = locations.next();
                if(opCount == 0 && location != null){
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
                country = location.getCountryName();
                if(country == null) {
                    country = "";
                } else {
                    country =  ", " + country;
                }
                raw += location+"\n";
                optionArray[opCount] = location.getAddressLine(0)+", "
                        +location.getAddressLine(1)+country+"\n";
                opCount ++;
            }
            // Log the returned data
            Log.d(MainActivity.APP_TAG, raw);
            Log.d(MainActivity.APP_TAG, "\nOptions:\n");
            for(int i=0; i<opCount; i++){
                Log.i(MainActivity.APP_TAG, "("+(i+1)+") "+optionArray[i]);
            }
            Log.d(MainActivity.APP_TAG, "latitude=" + latitude + ";longitude=" + longitude);
        } catch (Exception e){
            Log.d(MainActivity.APP_TAG, "I/O Failure; do you have a network connection?",e);
        }
    }
}

Links expire so i have pasted complete code above but just in case if you would like to see complete code then its available at : https://github.com/gosaliajigar/CSC519/tree/master/CSC519_HW4_89753

链接过期,所以我粘贴了上面的完整代码,但是如果您想看到完整的代码,那么它的可用地址是:https://github.com/gosaliajigar/CSC519/tree/master/CSC519_HW4_89753