针对业务需求,需要在 web 端、H5 显示高德地图与谷歌地图的底图图层切换;
- 可找到高德地图的底图图层切换 API,高德地图 API 只有 1.4 版本以及以下版本才能设置英文底图;
- 先在 index.html 页面引入高德地图的 API 地址
<script src="https://webapi.amap.com/maps?v=1.4.15&key=xxxxxxxxxxxxx&&plugin=AMap.Scale,AMap.OverView,AMap.MarkerCluster,AMap.ToolBar,AMap.PolyEditor,AMap.MouseTool,AMap.MapType,AMap.RangingTool,AMap.CitySearch,AMap.Weather,AMap.DistrictSearch,AMap.Geocoder"></script>
- 高德地图的功能代码
const langStr = g_i18n.global.locale.value === 'en' ? 'en' : 'zh_cn'
// 初始化地图
const map = new AMap.Map('map-wrap', {
resizeEnable: true,
expandZoomRange: true,
center: [114.03281, 22.612002], // 深圳市龙华区
zoom: 15,
zooms: [3, 20],
mapStyle: 'amap://styles/fresh',
lang: langStr
})
initMapLayer()
function initMapLayer() {
map &&
map.setLayers([
props.mapType === 'AMAP' ? getAMapLayer() : getGoogleMapLayer()
])
}
function getAMapLayer() {
return props.enableSatellite
? // 卫星地图
new AMap.TileLayer.Satellite({
zIndex: 1
})
: // 普通地图
new AMap.TileLayer({
zIndex: 1
})
}
- 谷歌官方提供的图层是存在访问限制的,需要通过服务器代理访问,以下是谷歌地图的底图图层切换代码
function getGoogleMapLayer() {
/**
* Google 的切片图层中,lyrs 参数可以是
* h = 路网
* m = 标准地图
* p = 地形图
* r = 某种改变的地图
* s = 卫星图(无路网)
* t = 地形图(无路网)
* y = 混合地图(带路网的卫星图)
*/
const lyrs = props.enableSatellite ? 's' : 'm'
const hl = g_i18n.global.locale.value === 'en' ? 'en-us' : 'zh-CN'
return new AMap.TileLayer({
tileUrl: `https://googlemap.xxxxx.com/maps/vt/lyrs=${lyrs}@142&hl=${hl}&gl=cn&x=[x]&y=[y]&z=[z]&s=Galile`,
// tileUrl: `http://www.google.com/maps/vt/lyrs=${lyrs}@142&hl=${hl}&gl=cn&x=[x]&y=[y]&z=[z]&s=Galile`,
zIndex: 1
})
}