Android 简明教程

Android - Google Maps

Android 允许我们在应用程序中集成 Google 地图。你可以在地图上展示任何位置,也可以在地图上展示不同路线等。你还可以根据自己的选择自定义地图。

Android allows us to integrate google maps in our application. You can show any location on the map , or can show different routes on the map e.t.c. You can also customize the map according to your choices.

Google Map - Layout file

现在,你必须将地图片段添加到 xml 布局文件中。其语法如下 -

Now you have to add the map fragment into xml layout file. Its syntax is given below −

<fragment
   android:id="@+id/map"
   android:name="com.google.android.gms.maps.MapFragment"
   android:layout_width="match_parent"
   android:layout_height="match_parent"/>

Google Map - AndroidManifest file

接下来需要做的就是向 AndroidManifest.XML 文件添加一些权限以及 Google 地图 API 密钥。其语法如下 -

The next thing you need to do is to add some permissions along with the Google Map API key in the AndroidManifest.XML file. Its syntax is given below −

<!--Permissions-->

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.
   READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<!--Google MAP API key-->

<meta-data
   android:name="com.google.android.maps.v2.API_KEY"
   android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />

Customizing Google Map

你可以轻松地从其默认视图自定义 Google 地图,并根据你的需求进行更改。

You can easily customize google map from its default view , and change it according to your demand.

Adding Marker

你可以在地图上放置一个标记并附上文本,以显示你的位置。这可以通过 addMarker() 方法完成。其语法如下 -

You can place a maker with some text over it displaying your location on the map. It can be done by via addMarker() method. Its syntax is given below −

final LatLng TutorialsPoint = new LatLng(21 , 57);
Marker TP = googleMap.addMarker(new MarkerOptions()
   .position(TutorialsPoint).title("TutorialsPoint"));

Changing Map Type

你还可以更改地图的类型。共有四种不同的地图类型, 每种类型都会提供不同的地图视图。这些类型包括普通、混合、卫星和地形。你可以按如下方式使用它们

You can also change the type of the MAP. There are four different types of map and each give a different view of the map. These types are Normal,Hybrid,Satellite and terrain. You can use them as below

googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Enable/Disable zoom

你还可以通过调用 setZoomControlsEnabled(boolean) 方法来启用或禁用地图中的缩放手势。其语法如下 -

You can also enable or disable the zoom gestures in the map by calling the setZoomControlsEnabled(boolean) method. Its syntax is given below −

googleMap.getUiSettings().setZoomGesturesEnabled(true);

除了这些自定义功能外,谷歌地图类中还有其他方法,可以帮助你进一步自定义地图。它们列在下面 -

Apart from these customization, there are other methods available in the GoogleMap class , that helps you more customize the map. They are listed below −

Sr.No

Method & description

1

addCircle(CircleOptions options) This method add a circle to the map

2

addPolygon(PolygonOptions options) This method add a polygon to the map

3

addTileOverlay(TileOverlayOptions options) This method add tile overlay to the map

4

animateCamera(CameraUpdate update) This method Moves the map according to the update with an animation

5

clear() This method removes everything from the map.

6

getMyLocation() This method returns the currently displayed user location.

7

moveCamera(CameraUpdate update) This method repositions the camera according to the instructions defined in the update

8

setTrafficEnabled(boolean enabled) This method Toggles the traffic layer on or off.

9

snapshot(GoogleMap.SnapshotReadyCallback callback) This method Takes a snapshot of the map

10

stopAnimation() This method stops the camera animation if there is one in progress

Example

以下是一个演示 GoogleMap 类使用方法的示例。它创建了一个基础 M 应用程序,供您在其中浏览地图。

Here is an example demonstrating the use of GoogleMap class. It creates a basic M application that allows you to navigate through the map.

要使用此示例,你可以在实际设备或模拟器上运行此示例。

To experiment with this example , you can run this on an actual device or in an emulator.

按照以下所示使用 Google 地图活动创建一个项目:

Create a project with google maps activity as shown below −

google maps

它将打开以下屏幕并复制 API 密钥的控制台 URL,如下图所示:

It will open the following screen and copy the console url for API Key as shown below −

google maps1

复制它并粘贴到浏览器中。它将显示以下屏幕:

Copy this and paste it to your browser. It will give the following screen −

google maps2

单击继续,然后单击创建 API 密钥,它将显示以下屏幕:

Click on continue and click on Create API Key then it will show the following screen

google maps3

以下是 activity_main.xml 的内容。

Here is the content of activity_main.xml.

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:map="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/map"
   android:name="com.google.android.gms.maps.SupportMapFragment"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.example.tutorialspoint7.myapplication.MapsActivity" />

以下为 MapActivity.java 的内容。

Here is the content of MapActivity.java.

package com.example.tutorialspoint7.myapplication;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
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 MapsActivity extends FragmentActivity implements OnMapReadyCallback {

   private GoogleMap mMap;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_maps);
      // Obtain the SupportMapFragment and get notified when the map is ready to be used.
      SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
         .findFragmentById(R.id.map);
      mapFragment.getMapAsync(this);
   }

   /**
      * Manipulates the map once available.
      * This callback is triggered 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.
      * This method will only be triggered once the user has installed
         Google Play services and returned to the app.
   */

   @Override
   public void onMapReady(GoogleMap googleMap) {
      mMap = googleMap;
      // Add a marker in Sydney and move the camera
      LatLng TutorialsPoint = new LatLng(21, 57);
      mMap.addMarker(new
         MarkerOptions().position(TutorialsPoint).title("Tutorialspoint.com"));
      mMap.moveCamera(CameraUpdateFactory.newLatLng(TutorialsPoint));
   }
}

下面是 AndroidManifest.xml 文件的内容。

Following is the content of AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tutorialspoint7.myapplication">

   <!--
      The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
      Google Maps Android API v2, but you must specify either coarse or fine
      location permissions for the 'MyLocation' functionality.
   -->

   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
   <uses-permission android:name="android.permission.INTERNET" />
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">

      <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key
         that is used to sign the APK for publishing.
         You can define the keys for the debug and
            release targets in src/debug/ and src/release/.
      -->

      <meta-data
         android:name="com.google.android.geo.API_KEY"
         android:value="AIzaSyAXhBdyKxUo_cb-EkSgWJQTdqR0QjLcqes" />

      <activity
         android:name=".MapsActivity"
         android:label="@string/title_activity_maps">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>

</manifest>

输出应如下所示:

Output should be like this −

google maps4