api官网:https://developers.google.com/maps/documentation/javascript/overview
api中文:http://www.bigemap.com/offlinemaps/google/polyline_class.html
- 申请秘钥
- GoogleMap api引入
<script src="https://maps.googleapis.com/maps/api/js?key=秘钥&libraries=drawing&v=weekly"></script>
参数说明
sensor:(true or false)说明程序是否使用传感器来定位位置
callback:(函数名)用于先加载页面,页面加载完后载入地图的情况,函数会在api完全载入后执行
libraries:使用到的内置库,drawing为绘图图
- 初始化地图
this.map = new google.maps.Map(document.getElementById("map"), {
center: {lat: 22.344335377436714, lng: 114.16939267248834}, // 设置地图中心位置
zoom: 15, // 地图缩放等级(1~20整数)数值越大,显示越细
mapTypeId: "roadmap",
disableDefaultUI: true, // 禁用默认的UI组件
});
- 添加多个标记点
GoogleMap自带的Marker类即可创建标记点,由于有需要标记点添加title的需求,因此这里用到了一个扩展类MarkerWithLabel
// this.map.setCenter(null); // 清除中心点
// this.map.setZoom(15); // 设置地图缩放登记
// 存储所有marker对象,每次重新标记时需要清除标记this.markerArray[i].setMap(null);
this.markerArray = [];
// 存储所有标记位置
this.LatLngList.push(new google.maps.LatLng(纬度, 经度));
// 创建标记点
var marker = new google.maps.MarkerWithLabel({
icon: iconUrl,
map: this.map,
position: (纬度, 经度),
labelContent: key, //需要显示的标题的内容
labelAnchor: new google.maps.Point(27, 39), //当前标题基于marker左上角的偏移
labelClass: labelClass, //标题class
labelStyle: {} //标题的style样式,
});
this.markerArray.push(marker);
// 创建信息窗口
var infoWindow = new google.maps.InfoWindow({
maxWidth : 300,
content: '<div style="font-size: 14px;">啦啦啦</div>'
})
// 监听信息窗口
google.maps.event.addListener(marker, 'mouseover', function () {
infoWindow.open(this.map, marker);
});
// 多个标记点不知道中心位置时需要设置最佳视图
let bounds = new google.maps.LatLngBounds(); // 构建坐标矩形
for (var i = 0, LtLgLen = this.LatLngList.length; i < LtLgLen; i++) {
bounds.extend(this.LatLngList[i]); // 写入坐标
}
this.map.fitBounds(bounds); // 调整地图,设置最佳视野