安卓调用百度地图和苹果调用百度地图代码
时间: 2023-09-15 19:21:33 浏览: 265
安卓调用百度地图代码示例:
1. 在 AndroidManifest.xml 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
```
2. 在 build.gradle 文件中添加以下依赖:
```
implementation 'com.baidu.android:map-sdk:5.3.0'
```
3. 在布局文件中添加 MapView 控件:
```xml
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
4. 在 Activity 中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private MapView mMapView = null;
private BaiduMap mBaiduMap = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化地图
mMapView = findViewById(R.id.bmapView);
mBaiduMap = mMapView.getMap();
// 显示地图
LatLng latLng = new LatLng(39.915071, 116.403907);
MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(latLng);
mBaiduMap.setMapStatus(mapStatusUpdate);
// 添加标记
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("北京市");
markerOptions.draggable(false);
Marker marker = (Marker) mBaiduMap.addOverlay(markerOptions);
}
@Override
protected void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mMapView.onPause();
}
}
```
苹果调用百度地图代码示例:
1. 在 Xcode 项目中创建桥接文件(Bridging-Header.h),并添加以下内容:
```objective-c
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
```
2. 在 Podfile 文件中添加以下依赖:
```
pod 'BaiduMapKit'
```
3. 在 Swift 代码中添加以下代码:
```swift
import UIKit
import BaiduMapKit
class ViewController: UIViewController, BMKMapViewDelegate {
var mapView: BMKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView = BMKMapView(frame: view.bounds)
mapView.delegate = self
view.addSubview(mapView)
let coordinate = CLLocationCoordinate2D(latitude: 39.915071, longitude: 116.403907)
let annotation = BMKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "北京市"
mapView.addAnnotation(annotation)
let region = BMKCoordinateRegion(center: coordinate, span: BMKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
mapView.setRegion(region, animated: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
mapView.viewWillAppear()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
mapView.viewWillDisappear()
}
func mapViewDidFinishLoading(_ mapView: BMKMapView!) {
print("地图加载完成")
}
}
```
阅读全文