Javascript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>根据地址获取经纬度</title>
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=密钥"></script>
<style>
.anchorBL {
display:none;
}
</style>
</head>
<body>
<div class="box" style="width: 700px; margin: 150px auto;">
<input type="text" style="margin-bottom: 20px;"
placeholder="请输入查询地址" id="addr">
<button onclick="getpoint()">获取经纬度</button>
<div id="map" style="width: 100%; height: 500px;"></div>
<div id="latlng"></div>
</div>
</body>
<script>
const map = new BMap.Map('map');
map.centerAndZoom('北京', 15)
map.enableScrollWheelZoom();
map.enableContinuousZoom();
const localSearch = new BMap.LocalSearch(map);
localSearch.enableAutoViewport();
function getpoint () {
const val = document.getElementById('addr').value;
localSearch.setSearchCompleteCallback(function(res) {
map.clearOverlays();
const poi = res.getPoi(0);
map.centerAndZoom(poi.point, 15);
const marker = new BMap.Marker(new BMap.Point(poi.point.lng, poi.point.lat));
map.addOverlay(marker);
const latlng = document.getElementById('latlng');
latlng.innerHTML = `经度:${poi.point.lng},纬度:${poi.point.lat}`;
});
localSearch.search(val);
}
</script>
</html>
angularJs
- 引入百度地图api:
注意:需在index.html文件中进行引用
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=密钥"></script>
- 创建map组件文件夹及三个文件如下:
- html文件:
<div class="main-content">
<div id="map"></div>
</div>
- css文件:
.main-content {
width: 100%;
height: 100%;
}
#map {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
.anchorBL {
display: none;
}
- ts文件:
import { Component, OnInit, AfterViewInit, Input, OnChanges } from '@angular/core';
import { NzMessageService } from "ng-zorro-antd";
declare var BMap: any;
@Component({
selector: 'my-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css'],
})
export class mapComponent implements OnInit, AfterViewInit, OnChanges {
constructor(
private _message: NzMessageService
) { }
@Input() addr: any;
map = null;
ngOnInit(): void {
this.map = new BMap.Map('map');
const point = new BMap.Point(116.404, 39.915);
this.map.centerAndZoom(point, 15);
this.map.enableScrollWheelZoom(true);
}
ngAfterViewInit() {
setTimeout(() => { }, 10);
}
ngOnChanges() {
const that = this;
if (this.map) {
const maps = this.map;
const localSearch = new BMap.LocalSearch(maps);
localSearch.enableAutoViewport();
maps.clearOverlays();
localSearch.setSearchCompleteCallback(function(searchResult) {
const poi = searchResult.getPoi(0);
if (poi) {
maps.centerAndZoom(poi.point, 15);
const marker = new BMap.Marker(new BMap.Point(poi.point.lng, poi.point.lat));
maps.addOverlay(marker);
} else {
that._message.warning('无法定位');
}
});
localSearch.search(this.addr);
}
}
}
- 因为对angular语言不熟悉,为防止误导,此处省略组件注册步骤;
- 在html中引入使用:
<my-map style="height: 500px; width:700px;" [addr]="addr"></my-map>
addr = '';
setAddr() {
console.log('baidu-map');
this.addr = this.inputVal;
}