用户在我的应用程序中按下按钮后,我想打开标准Google Map应用程序并显示特定位置。我该怎么做? (不使用com.google.android.maps.MapView
)
答案 0 :(得分:217)
您应该创建一个带有地理URI的Intent
对象:
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
如果您想指定地址,则应使用其他形式的地理URI:geo:0,0?q=address
。
参考:https://developer.android.com/guide/components/intents-common.html#Maps
答案 1 :(得分:90)
您也可以使用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);
或者您可以确保仅使用Google地图应用,这样可以阻止意图过滤器(对话框)显示,使用
intent.setPackage("com.google.android.apps.maps");
像这样:
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);
或者您可以通过在每组坐标后面的括号内添加一个字符串来为位置添加标签,如下所示:
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);
要将用户当前位置用作起点(遗憾的是我还没有找到标记当前位置的方法),请按以下方式删除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);
为了完整性,如果用户没有安装地图应用程序,那么捕获ActivityNotFoundException是一个好主意,就像@TonyQ所述,然后我们可以在没有地图应用限制的情况下再次启动活动,我们可以非常肯定我们最终永远不会去Toast,因为互联网浏览器也是启动这个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();
}
}
修改强>
对于路线,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);
答案 2 :(得分:40)
使用String格式会有所帮助,但您必须完全了解区域设置。在德国浮动将用逗号分隔而不是一个点。
在语言环境英语上使用String.format("geo:%f,%f",5.1,2.1);
,结果将为"geo:5.1,2.1"
,但使用区域设置德语,您将获得"geo:5,1,2,1"
您应该使用英语区域设置来防止此行为。
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
要将标签设置为地理位置,您可以使用以下方法扩展地理位置:
!!! 但请注意,geo-uri仍在开发中 http://tools.ietf.org/html/draft-mayrhofer-geo-uri-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);
答案 3 :(得分:8)
从google检查此页面:
http://developer.android.com/guide/appendix/g-app-intents.html
您可以使用
形式的URIgeo:latitude,longitude
打开Google地图查看器并将其指向某个位置。
答案 4 :(得分:6)
有时如果没有与geo相关的应用程序:protocal, 你可以使用try-catch来获取ActivityNotFoundException来处理它。
当您使用默认情况下未安装谷歌地图的androVM等仿真器时会发生这种情况。
答案 5 :(得分:6)
您还可以使用下面的代码段,以此方式在启动意图之前检查是否存在Google地图。
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);
}
参考:https://developers.google.com/maps/documentation/android-api/intents
答案 6 :(得分:0)
我有一个示例应用,我在其中准备意图并将意图中的CITY_NAME传递给地图标记活动,该活动最终通过Geocoder使用CITY_NAME计算经度和纬度。
以下是启动地图标记活动和完整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);
}
}
}
链接过期,所以我粘贴了上面的完整代码,但万一您希望看到完整的代码,请访问:https://github.com/gosaliajigar/CSC519/tree/master/CSC519_HW4_89753
答案 7 :(得分:0)
要转到带有PIN的位置,请使用:
String uri = "http://maps.google.com/maps?q=loc:" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);
对于不带别针的,请在uri中使用它:
String uri = "geo:" + destinationLatitude + "," + destinationLongitude;
答案 8 :(得分:0)
这是用Kotlin写的,如果找到它,它将打开地图应用并放置该点,让您开始旅程:
val gmmIntentUri = Uri.parse("http://maps.google.com/maps?daddr=" + adapter.getItemAt(position).latitud + "," + adapter.getItemAt(position).longitud)
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage("com.google.android.apps.maps")
if (mapIntent.resolveActivity(requireActivity().packageManager) != null) {
startActivity(mapIntent)
}
将requireActivity()
替换为Context
。
答案 9 :(得分:0)
此外,您还可以使用 external_app_launcher:https://pub.dev/packages/external_app_launcher
要知道是否已安装:
await LaunchApp.isAppInstalled(androidPackageName: 'com.google.android.maps.MapView', iosUrlScheme: 'comgooglemaps://');
打开:
await LaunchApp.openApp(
androidPackageName: 'com.google.android.maps.MapView',
iosUrlScheme: 'comgooglemaps://',
);
答案 10 :(得分:0)
Uri gmmIntentUri = Uri.parse("google.streetview:cbll=46.414382,10.013988");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);