在本教程中,我们将了解如何开发一个简易的安卓地图应用。该应用的主要功能是在地图中显示用户的位置,并允许用户检索特定地址 。为了实现这个目标,我们将使用安卓 Studio、谷歌 Maps API以及Geocoding API。
第一步准备开发环境
1. 下载并安装安卓 Studio访问https://developer.安卓.com/studio 并根据操作系统下载安装包,遵循安装向导的指引安装。
2. 创建一个新项目打开安卓 Studio,从欢迎页面选择“New 安卓 Studio Project”。接下来填写应用名称、包名、项目存储位置,然后选择所需的最低API级别。选择空项目进行开发,接着点击“Finish”。
第二步集成谷歌 Maps API
3. 获取API密钥访问https://console.developers.google.com/ ,使用谷歌帐户登入。点击创建新项目,然后在项目中启用谷歌 Maps API 和 Geocoding API。 在API库中查找所需API,并在适用的API页面上点击“启用”。 API启用后,点击“创建凭据”生成API密钥。
4. 集成到安卓 Studio项目在安卓Manifest.xml文件中,添加谷歌 Maps元数据,将API,KEY替换为实际的API密钥
```
安卓:name=com.google.安卓.geo.API,KEY
安卓:value=YOUR,API,KEY/>
```
第三步添加谷歌 Maps视图
5. 添加必要的权限在安卓Manifest.xml文件内添加如下权限
```xml
```
6. 在activity,main.xml文件中将根布局更改为RelativeLayout,并添加SupportMapFragment如下
```xml
安卓:id=@+id/map
安卓:layout,width=match,parent
安卓:layout,height=match,parent
安卓:name=com.google.安卓.gms.maps.SupportMapFragment/>
```
7. 在MainActivity.java文件中完成如下内容
```java
import com.google.安卓.gms.maps.CameraUpdateFactory;
import com.google.安卓.gms.maps.谷歌Map;
import com.google.安卓.gms.maps.OnMapReadyCallback;
import com.google.安卓.gms.maps.SupportMapFragment;
import com.google.安卓.gms.maps.model.LatLng;
import com.google.安卓.gms.maps.model.MarkerOptions;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private 谷歌Map mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity,main);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(谷歌Map googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151); // 将地图中心初始定位在悉尼纬度纬度上
mMap.addMarker(new MarkerOptions().position(sydney).title(Marker in Sydney)); // 在地图上添加一个标记
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 10)); // 将相机移至悉尼,并设置缩放级别为10
}
}
```
第四步显示用户当前位置
8. 在MainActivity.java中,为谷歌Map添加LocationSource和LocationListener对象,如下所示
```java
private 谷歌Map mMap;
private LocationManager locationManager;
private LocationListener locationListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
locationManager = (LocationManager) getSystemService(Context.LOCATION,SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng).title(Your Location));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
}
// ...
}
}
```
9. 添加申请定位权限的逻辑,并在得到权限后请求位置更新
```java
private static final int LOCATION,PERMISSION,REQUEST,CODE = 123;
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS,FINE,LOCATION) != PackageManager.PERMISSION,GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS,FINE,LOCATION}, LOCATION,PERMISSION,REQUEST,CODE);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS,PROVIDER, 2000, 10, locationListener);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION,PERMISSION,REQUEST,CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION,GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS,FINE,LOCATION}, LOCATION,PERMISSION,REQUEST,CODE);
}
}
}
```
第五步添加检索功能
10. 在activity,main.xml文件中添加一个SearchView控件,如下所示
```xml
安卓:id=@+id/searchView
安卓:layout,width=match,parent
安卓:layout,height=wrap,content/>
```
11. 在MainActivity.java中,实现SearchView.OnQueryTextListener接口,并处理查询提交
```java
import 安卓x.appcompat.widget.SearchView;
import com.google.安卓.gms.maps.model.BitmapDescriptorFactory;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, SearchView.OnQueryTextListener {
private 谷歌Map mMap;
// ...
private SearchView searchView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
searchView = findViewById(R.id.searchView);
searchView.setOnQueryTextListener(this);
}
@Override
public boolean onQueryTextSubmit(String query) {
Geocoder geocoder = new Geocoder(this);
List
addresses = null;try {
addresses = geocoder.getFromLocationName(query, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && !addresses.isEmpty()) {
Address address = addresses.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng).title(Your Location).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE,AZURE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
} else {
Toast.makeText(this, Unable to find the location :(, Toast.LENGTH,SHORT).show();
}
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
}
```
至此,你已经成功开发了一个基本的安卓地图应用,它可以显示用户的当前位置和检索特定地址。你可以在此基础上追加更多功能,例如添加其他类型的