高德/百度地图常用api

//amap.js

export default {
    //初始化地图
    initMap (options) {
        let _self = this

        return new Promise((resolve) => {
            _self.map = new AMap.Map((options && options.id) || 'allmap', {
                resizeEnable    : true,
                touchZoomCenter : 1,
                doubleClickZoom : false,
            })

            _self.map.on('dblclick', function () {
                _self.map.zoomIn()
            })

            resolve(_self.map)
        })
    },
    setZoomAndCenter (options) {
        if (!options.longitude || !options.latitude) return false
        let _self = this
        _self.map.setZoomAndCenter(
            options.zoom || 17,
            [options.longitude, options.latitude]
        )
    },
    setCity (options) {
        if (!options.city) return false

        let _self = this
        _self.map.setCity(options.city, options.zoom || 17)
    },
    listenDragend (cb) {
        let _self = this
        _self.map.on('dragend', function () {
            cb && cb()
        })
    },
    autocomplete ({ keyword, city, province }, cb) {
        if (!keyword) {
            throw new Error('参数错误')
        }

        AMap.plugin(['AMap.Autocomplete'], function () {
            let autocomplete = new AMap.Autocomplete({
                'city' : city || province || '全国',
            })

            autocomplete.search(keyword, function (status, res) {
                if (status === 'complete' && res.info === 'OK') {
                    let _tips = res['tips'] || []
                    let _pois = []
                    for (let i in _tips) {
                        let _item = _tips[i] || {}
                        let _point = _item.location || {}
                        if (Object.keys(_point).length <= 0) continue
                        _item['address'] = typeof _item['address'] !== 'string' ? _item['name'] : _item['address']
                        _item['longitude'] = _point['lng']
                        _item['latitude'] = _point['lat']
                        _pois.push(_item)
                    }
                    cb && cb({
                        'pois'     : _pois,
                        'province' : province || '',
                        'city'     : city || province || '',
                    })
                } else {
                    cb && cb({})
                }
            })
        })
    }, //关键词搜索
    searchByKeyword ({ keyword, city, province, page, pageSize, autoFitView, showCover, longitude, latitude }, cb) {
        if (longitude && latitude) {
            this.searchNearby({
                'longitude' : longitude || 0,
                'latitude'  : latitude || 0
            }, function (res) {
                cb && cb(res)
            })
        } else {
            if (!keyword) {
                throw new Error('参数错误')
            }
            AMap.service(['AMap.PlaceSearch'], function () {
                let placeSearch = new AMap.PlaceSearch({
                    'city'        : city || province || '全国',
                    'pageSize'    : pageSize || 20,
                    'pageIndex'   : page || 1,
                    'autoFitView' : autoFitView || false,
                    'showCover'   : showCover || false,
                    'extensions'  : 'all'
                })

                placeSearch.search(keyword, function (status, res) {
                    if (status === 'complete' && res.info === 'OK') {
                        let _poiList = res['poiList'] || {}
                        let _pois = _poiList['pois'] || []
                        for (let i in _pois) {
                            let _item = _pois[i] || {}
                            let _point = _item.location || {}
                            _item['longitude'] = _point['lng']
                            _item['latitude'] = _point['lat']
                        }
                        cb && cb({
                            'pois'     : _pois,
                            'province' : _pois[0]['pname'] || '',
                            'city'     : _pois[0]['cityname'] || '',
                        })
                    } else {
                        cb && cb({})
                    }
                })
            })
        }
    }, //周边检索
    searchNearby (options, cb) {
        let _self = this
        AMap.plugin('AMap.Geocoder', function () {
            let geocoder = new AMap.Geocoder({
                extensions : 'all'
            })

            let _lnglat = [options.longitude, options.latitude]
            geocoder.getAddress(_lnglat, function (status, res) {
                if (status === 'complete' && res.info === 'OK') {
                    let _regeocode = res['regeocode'] || {}
                    let _pois = _regeocode['pois'] || []
                    let _addressComponent = _regeocode['addressComponent'] || {}
                    for (let i in _pois) {
                        let _item = _pois[i] || {}
                        let _point = _item.location || {}
                        _item['longitude'] = _point['lng']
                        _item['latitude'] = _point['lat']
                    }
                    cb && cb({
                        'pois'     : _pois,
                        'province' : _addressComponent['province'] || '',
                        'city'     : _addressComponent['city'] || _addressComponent['province'] || '',
                    })
                } else {
                    cb && cb({})
                }
            })
        })
    },
    //获取当前位置
    getCurrentPosition (cb) {
        let _self = this
        AMap.plugin('AMap.Geolocation', function () {
            let geolocation = new AMap.Geolocation({
                timeout        : 5000,
                zoomToAccuracy : true
            })
            geolocation.getCurrentPosition(function (status, res) {
                if (status === 'complete' && res.info === 'SUCCESS') {
                    let _poi = res['position'] || {}
                    let _addressComponent = res['addressComponent'] || {}
                    if (!_poi.lng || !_poi.lat) {
                        _poi = _self.defPoint
                    }

                    cb && cb({
                        'longitude' : _poi.lng,
                        'latitude'  : _poi.lat,
                        'province'  : _addressComponent['province'] || '',
                        'city'      : _addressComponent['city'] || _addressComponent['province'] || '',
                    })
                } else {
                    cb && cb(_self.defPoint)
                }
            })
        })
    },
    /**
     *
     */
    getPoint ({ lat, lng }) {
        if (!lat || !lng) {
            throw new Error('参数错误')
        }

        return new AMap.LngLat(lng, lat)
    },
    /**
     * 创建覆盖物
     */
    createMarker ({ lat, lng, icon, content, extData = null, zIndex = 100 }) {
        if (!lat || !lng) {
            throw new Error('参数错误')
        }

        let _marker = new AMap.Marker({
            'position' : new AMap.LngLat(lng, lat),
            'offset'   : new AMap.Pixel(-20, -40),
            'content'  : content,
            'icon'     : new AMap.Icon({
                'image'     : icon,
                'size'      : new AMap.Size(38, 43),
                'imageSize' : new AMap.Size(38, 43)
            }),
            'zIndex'   : zIndex,
            'extData'  : extData,
        })
        return _marker
    },
    /**
     * 添加覆盖物
     */
    addMarker ({ map, lat, lng, icon, content, extData = null, zIndex = 100 },cb) {
        if (!map || !lat || !lng) {
            throw new Error('参数错误')
        }

        let _marker = new AMap.Marker({
            'position' : new AMap.LngLat(lng, lat),
            'offset'   : new AMap.Pixel(-20, -40),
            'content'  : content,
            'icon'     : new AMap.Icon({
                'image'     : icon,
                'size'      : new AMap.Size(38, 43),
                'imageSize' : new AMap.Size(38, 43)
            }),
            'zIndex'   : zIndex,
            'extData'  : extData,
        })
        map && map.add(_marker)
        // return _marker
        cb && cb(_marker)

    },
    /**
     *
     */
    addLabel ({ marker, text, time }) {
        if (!marker || !text) {
            throw new Error('参数错误')
        }

        marker && marker.setLabel({
            offset    : new AMap.Pixel(0, -1), //设置文本标注偏移量
            content   : '<div style="border: 1px solid #ff7326;padding: 5px 10px;font-size: 16px;border-radius: 5px;"><div>'+ text+'</div><div style="font-size: 12px;color: #999999">'+ time +'</div></div>', //设置文本标注内容
            direction : 'top', //设置文本标注方位
        })
    },
    /**
     *
     */
    setViewport ({
                     map,
                     overlays,
                     marginTop = 20,
                     marginLeft = 20,
                     marginRight = 20,
                     marginBottom = 20,
                     maxZoom = 16
                 }) {
        if (!map || !overlays) {
            throw new Error('参数错误')
        }
        map && map.setFitView(overlays, true, [marginTop, marginBottom, marginLeft, marginRight], maxZoom)
    },
    /**
     *
     */
    geocoder ({ lat, lng }) {
        return new Promise((resolve, reject) => {
            if (!lat || !lng) {
                reject(new Error('参数错误'))
            }

            AMap.plugin('AMap.Geocoder', function () {
                let geocoder = new AMap.Geocoder({
                    extensions : 'all'
                })

                let _lnglat = [lng, lat]
                geocoder.getAddress(_lnglat, function (status, res) {
                    if (status === 'complete' && res.info === 'OK') {
                        let _regeocode = res['regeocode'] || {}
                        let _pois = _regeocode['pois'] || []
                        let _item = _pois[0] || {}
                        let _point = _item.location || {}
                        let _addressComponent = _regeocode['addressComponent'] || {}
                        _item['longitude'] = _point['lng']
                        _item['latitude'] = _point['lat']
                        _item['province'] = _addressComponent['province'] || ''
                        _item['city'] = _addressComponent['city'] || _addressComponent['province'] || ''
                        _item['adcode'] = _addressComponent['adcode'] || ''
                        _item['address'] = _regeocode['formattedAddress'] || ''
                        resolve(_item)
                    } else {
                        resolve({})
                    }
                })
            })
        })
    },
    /**
     *
     */
    clearOverlays ({ map }) {
        if (!map) {
            throw new Error('参数错误')
        }

        map && map.clearMap()
    },
    /**
     *
     */
    setCenter ({ map, lat, lng }) {
        if (!map || !lat || !lng) {
            throw new Error('参数错误')
        }

        map && map.setCenter([lng, lat])
    },
    /**
     * 规划步行路线+绘制骑行路线
     */
    drawWalkingPath ({ map, origin, destination }, cb) {
        let _self = this
        if (!map || !origin || !destination) {
            throw new Error('参数错误')
        }
        _self.walkingSearch({
            'map'         : map,
            'origin'      : origin,
            'destination' : destination,
        }, function ({ route }) {
            let path = _self.routeToPath(route)
            let routeLine = _self.createPolyline({ 'path' : path })
            map && map.add(routeLine)
            let _distance = route.distance || ''
            if (_distance) {
                if (_distance < 1000) {
                    _distance = `${_distance}米`
                } else {
                    _distance = Math.ceil(_distance / 1000 * 10) / 10
                    _distance = `${_distance} 公里`
                }
            }
            cb && cb({
                'route'    : route,
                'distance' : _distance
            })
        })
    },
    walkingSearch ({ map, origin, destination }, cb) {
        if (!origin || !destination) {
            throw new Error('参数错误')
        }

        AMap.plugin(['AMap.Walking'], function () {
            var walking = new AMap.Walking()
            walking.search([origin.lng, origin.lat], [destination.lng, destination.lat], function (status, result) {
                if (status === 'complete') {
                    if (result.routes && result.routes.length) {
                        cb && cb({ 'route' : result.routes[0] })
                    } else {
                        cb && cb({ 'route' : {} })
                    }
                } else {
                    cb && cb({ 'route' : {} })
                }
            })
        })
    },
    walkingClear ({ walking }, cb) {
        walking && walking.clear()
    },
    routeToPath (route) {
        if (!route) {
            throw new Error('参数错误')
        }
        let path = []
        let steps = route.steps || []
        for (let i = 0, l = steps.length; i < l; i++) {
            let step = steps[i]
            for (let j = 0, n = step.path.length; j < n; j++) {
                path.push(step.path[j])
            }
        }
        return path
    },
    /**
     * 规划骑行路线+绘制骑行路线
     */
    drawRidingPath ({ map, origin, destination }, cb) {
        let _self = this
        if (!map || !origin || !destination) {
            throw new Error('参数错误')
        }
        _self.ridingSearch({
            'map'         : map,
            'origin'      : origin,
            'destination' : destination,
        }, function ({ route }) {
            let path = _self.routeToRidingPath(route)
            let routeLine = _self.createPolyline({ 'path' : path })
            map && map.add(routeLine)
            let _distance = route.distance || ''
            let _time = route.time ? (route.time / 60).toFixed(0) :''
            if (_distance) {
                if (_distance < 1000) {
                    _distance = `${_distance}米`
                } else {
                    _distance = Math.ceil(_distance / 1000 * 10) / 10
                    _distance = `${_distance} 公里`
                }
            }
            cb && cb({
                'route'    : route,
                'distance' : _distance,
                'time'     : _time
            })
        })
    },
    ridingSearch ({ map, origin, destination }, cb) {
        if (!origin || !destination) {
            throw new Error('参数错误')
        }

        AMap.plugin(['AMap.Riding'], function () {
            var riding = new AMap.Riding()
            riding.search([origin.lng, origin.lat], [destination.lng, destination.lat], function (status, result) {
                if (status === 'complete') {
                    if (result.routes && result.routes.length) {
                        cb && cb({ 'route' : result.routes[0] })
                    } else {
                        cb && cb({ 'route' : {} })
                    }
                } else {
                    cb && cb({ 'route' : {} })
                }
            })
        })
    },
    ridingClear ({ riding }, cb) {
        riding && riding.clear()
    },
    routeToRidingPath (route) {
        if (!route) {
            throw new Error('参数错误')
        }
        let path = []
        let rides = route.rides || []
        for (let i = 0, l = rides.length; i < l; i++) {
            let step = rides[i]
            for (let j = 0, n = step.path.length; j < n; j++) {
                path.push(step.path[j])
            }
        }
        return path
    },

    /**
     * 创建折线
     */
    createPolyline ({ path }) {
        if (!path) {
            throw new Error('参数错误')
        }

        return new AMap.Polyline({
            path         : path,
            isOutline    : true,
            outlineColor : '#FEE',
            borderWeight : 2,
            strokeWeight : 5,
            strokeColor  : '#00C3FF',
            lineJoin     : 'round'
        })
    }
}
//bmap.js


export default {
    //初始化地图
    initMap(options) {
        let _self = this

        return new Promise((resolve) => {
            _self.map = new BMap.Map((options && options.id) || 'allmap')
            _self.map.disableDoubleClickZoom()
            _self.map.enableScrollWheelZoom(true)

            _self.map.addEventListener('dblclick', function () {
                _self.map.zoomIn()
            })

            resolve(_self.map)
        })
    },
    setZoomAndCenter(options) {
        if (!options.longitude || !options.latitude) return false

        let _self = this
        _self.map.centerAndZoom(
            new BMap.Point(options.longitude, options.latitude),
            options.zoom || 17,
        )
    },
    setCity(options) {
        if (!options.city) return false

        let _self = this
        _self.map.centerAndZoom(options.city, options.zoom || 17)
    },
    listenDragend(cb) {
        let _self = this

        _self.map.addEventListener('dragend', function () {
            cb && cb()
        })
    },
    //关键词搜索
    autocomplete(options, cb) {
        let _self = this
        let _location = options.map || options.city
        let _localSearch = new BMap.LocalSearch(_location, {
            pageCapacity: 20,
            forceLocal: _location['forceLocal'] || true,
            onSearchComplete: function (res) {
                if (!res) return false

                let _pois = []
                for (let i = 0; i < res.getCurrentNumPois(); i++) {
                    _pois.push(res.getPoi(i))
                }
                for (let i in _pois) {
                    let _item = _pois[i] || {}
                    let _point = _item.point || {}
                    _item['name'] = _item['title']
                    _item['longitude'] = _point['lng']
                    _item['latitude'] = _point['lat']
                }
                x
                cb && cb({
                    'pois': _pois
                })
            }
        })

        _localSearch.search(options.keyword)
    },
    searchByKeyword(options, cb) {
        let _self = this
        let _location = options.map || options.city
        let _localSearch = new BMap.LocalSearch(_location, {
            pageCapacity: 20,
            forceLocal: _location['forceLocal'] || true,
            onSearchComplete: function (res) {
                if (!res) return false

                let _pois = []
                for (let i = 0; i < res.getCurrentNumPois(); i++) {
                    _pois.push(res.getPoi(i))
                }
                for (let i in _pois) {
                    let _item = _pois[i] || {}
                    let _point = _item.point || {}
                    _item['name'] = _item['title']
                    _item['longitude'] = _point['lng']
                    _item['latitude'] = _point['lat']
                }
                cb && cb({
                    'pois': _pois
                })
            }
        })

        _localSearch.search(options.keyword)
    },
    //周边检索
    searchNearby(options, cb) {
        let _self = this
        if (options.keyword) {
            let _localSearch = new BMap.LocalSearch(options.map, {
                pageCapacity: options.pageSize || 20,
                onSearchComplete: function (res) {
                    if (!res) return false

                    let _pois = []
                    for (let i = 0; i < res.getCurrentNumPois(); i++) {
                        _pois.push(res.getPoi(i))
                    }
                    for (let i in _pois) {
                        let _item = _pois[i] || {}
                        let _point = _item.point || {}
                        _item['name'] = _item['title']
                        _item['longitude'] = _point['lng']
                        _item['latitude'] = _point['lat']
                    }
                    cb && cb({
                        'pois': _pois,
                        'province': res['province'] || '',
                        'city': res['city'] || '',
                    })
                }
            })

            _localSearch.searchNearby(
                options.keyword,
                new BMap.Point(options.longitude, options.latitude),
                options.radius || 1000
            )
        } else {
            let _geo = new BMap.Geocoder()
            _geo.getLocation(new BMap.Point(options.longitude, options.latitude), function (res) {
                if (!res) return false

                let _pois = res.surroundingPois || []
                let _addressComponent = res.addressComponents || {}
                for (let i in _pois) {
                    let _item = _pois[i] || {}
                    let _point = _item.point || {}
                    _item['name'] = _item['title']
                    _item['longitude'] = _point['lng']
                    _item['latitude'] = _point['lat']
                }
                cb && cb({
                    'pois': _pois,
                    'province': _addressComponent['1'] || '',
                    'city': _addressComponent['city'] || '',
                })
            }, {poiRadius: options.radius || 1000, numPois: options.pageSize || 20})
        }
    },
    //获取当前位置
    getCurrentPosition(cb) {
        let _self = this
        let _geolocation = new BMap.Geolocation()
        _geolocation.enableSDKLocation()
        _geolocation.getCurrentPosition((res) => {
            if (!res) return false

            let _poi = {}
            if (!res.longitude || !res.latitude) {
                _poi.longitude = 116.615159
                _poi.latitude = 40.120991
            } else {
                _poi.longitude = res.longitude
                _poi.latitude = res.latitude
            }

            cb && cb({
                'longitude': _poi.longitude,
                'latitude': _poi.latitude,
                'province': res.address['province'] || '',
                'city': res.address['city'] || '',
            })
        }, {SDKLocation: true})
    },
    /**
     *
     */
    getPoint({lat, lng}) {
        if (!lat || !lng) {
            throw new Error('参数错误')
        }

        return new BMap.Point(lng, lat)
    },
    /**
     * 创建覆盖物
     */
    createMarker({lat, lng, icon, zIndex = 100}) {
        if (!lat || !lng || !icon) {
            throw new Error('参数错误')
        }

        let _marker = new BMap.Marker(new BMap.Point(lng, lat), {
            'icon': new BMap.Icon(icon, new BMap.Size(38, 43), {
                'imageSize': new BMap.Size(38, 43)
            }),
        })
        _marker.setZIndex(zIndex)
        return _marker
    },
    /**
     * 添加覆盖物
     */
    addMarker({map, lat, lng, icon, zIndex = 100}) {
        if (!map || !lat || !lng || !icon) {
            throw new Error('参数错误')
        }

        let _marker = new BMap.Marker(new BMap.Point(lng, lat), {
            'icon': new BMap.Icon(icon, new BMap.Size(38, 43), {
                'imageSize': new BMap.Size(38, 43)
            }),
        })
        _marker.setZIndex(zIndex)
        map && map.addOverlay(_marker)
        return _marker
    },
    /**
     * 添加覆盖物
     */
    addLabel({map, lat, lng, text, time}) {
        if (!map || !lat || !lng || !text) {
            throw new Error('参数错误')
        }
        let content = '<div><div>' + text + '</div><div  style="font-size: 12px;color: #999999">' + time + '</div></div>'
        let _label = new BMap.Label(content, {
            'position': new BMap.Point(lng, lat),
            'offset': new BMap.Size(-72, -60)
        })
        _label.setStyle({
            border: '1px solid #ff7326',
            padding: '5px 10px',
            fontSize: '16px',
            borderRadius: '5px',
        })
        map && map.addOverlay(_label)
        return _label
    },
    /**
     *
     */
    setViewport({
                    map,
                    points,
                    marginTop = 20,
                    marginLeft = 20,
                    marginRight = 20,
                    marginBottom = 20,
                    zoomFactor = 0
                }) {
        if (!map || !points) {
            throw new Error('参数错误')
        }

        map && map.setViewport(points, {
            margins: [marginTop, marginRight, marginBottom, marginLeft],
            zoomFactor: zoomFactor
        })
    },
    /**
     *
     */
    geocoder({lat, lng}) {
        return new Promise((resolve, reject) => {
            if (!lat || !lng) {
                reject(new Error('参数错误'))
            }

            let geo = new BMap.Geocoder()
            geo.getLocation(new BMap.Point(lng, lat), function (res) {
                let info = res.surroundingPois[0] || {}
                resolve(info)
            })
        })
    },
    /**
     *
     */
    clearOverlays({map}) {
        if (!map) {
            throw new Error('参数错误')
        }

        map && map.clearOverlays()
    },
    /**
     *
     */
    setCenter({map, lat, lng}) {
        if (!map || !lat || !lng) {
            throw new Error('参数错误')
        }

        map && map.setCenter(new BMap.Point(lng, lat))
    },
    /**
     * 规划步行路线
     */
    drawWalkingPath({map, origin, destination}, cb) {
        if (!map || !origin || !destination) {
            throw new Error('参数错误')
        }

        let walking = new BMap.WalkingRoute(map, {
            'renderOptions': {
                'map': map,
                'autoViewport': false
            },
            'onPolylinesSet': function (routes) {
                let searchRoute = routes[0].getPolyline() // 导航路线
                searchRoute.setStrokeColor('#00C3FF')
                map.addOverlay(routes)
            },
            'onMarkersSet': function (routes) {
                map.removeOverlay(routes[0].marker) // 删除起点
                map.removeOverlay(routes[routes.length - 1].marker) //删除终点
            },
            'onSearchComplete': function (results) {
                if (walking.getStatus() === BMAP_STATUS_SUCCESS) {
                    let plan = results.getPlan(0)
                    cb && cb({
                        'distance': plan.getDistance(),
                    })
                } else {
                    cb && cb({
                        'distance': '',
                    })
                }
            }
        })
        let start = new BMap.Point(origin.lng, origin.lat)
        let end = new BMap.Point(destination.lng, destination.lat)
        walking.search(start, end)
    },
    /**
     * 清除步行路线
     */
    walkingClear({walking}, cb) {
        walking && walking.clear()
        cb && cb()
    },
    /**
     * 规划骑行路线
     */
    drawRidingPath({map, origin, destination}, cb) {
        if (!map || !origin || !destination) {
            throw new Error('参数错误')
        }

        let riding = new BMap.RidingRoute(map, {
            'renderOptions': {
                'map': map,
                'autoViewport': false
            },
            'onPolylinesSet': function (routes) {
                let searchRoute = routes[0].getPolyline() // 导航路线
                searchRoute.setStrokeColor('#00C3FF')
                map.addOverlay(routes)
            },
            'onMarkersSet': function (routes) {
                map.removeOverlay(routes[0].marker) // 删除起点
                map.removeOverlay(routes[routes.length - 1].marker) //删除终点
            },
            'onSearchComplete': function (results) {
                if (riding.getStatus() === BMAP_STATUS_SUCCESS) {
                    let plan = results.getPlan(0)
                    let duration = plan.getDuration(false) ? (plan.getDuration(false) / 60).toFixed(0) : ''; // 单位为分钟

                    cb && cb({
                        'distance': plan.getDistance(),
                        'time': duration
                    })
                } else {
                    cb && cb({
                        'distance': '',
                        'time': ''
                    })
                }
            }
        })
        let start = new BMap.Point(origin.lng, origin.lat)
        let end = new BMap.Point(destination.lng, destination.lat)
        riding.search(start, end)
    },
    /**
     * 清除步行路线
     */
    ridingClear({riding}, cb) {
        riding && riding.clear()
        cb && cb()
    },
}
//@/lib/utils/map.js


import { load as loadScript } from './script'

class Map {
    constructor () {

    }

    loadMapJs (platform = '', key = '', secretKey = '') {
        platform = 'gaode'
        // key = '********'
        key = '********'//gaode
        secretKey =  '*******'
        return new Promise((resolve, reject) => {
            switch (platform) {
                case 'gaode':
                    window._AMapSecurityConfig = { 'securityJsCode' : secretKey }
                    if (window.AMap) {
                        return resolve()
                    }
                    loadScript(`https://webapi.amap.com/maps?v=1.4.15&key=${key}&callback=onApiLoaded`).then(() => {
                        resolve()
                    }).catch(() => {
                        reject()
                    })
                    break
                case 'baidu':
                    if (typeof BMap !== 'undefined') {
                        resolve()
                        return true
                    }

                    window.onBMapCallback = function () {
                        resolve()
                    }
                    console.log(3333333)

                    loadScript(`https://api.map.baidu.com/api?v=3.0&ak=${key}`).then(() => {
                        resolve()
                    }).catch(() => {
                        reject()
                    })
                    break
            }
        })
    }
}

const map = new Map()
export default map
//@/lib/utils/script.js


export function load (src) {
    if (!src) return Promise.reject()

    return new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.setAttribute('type', 'text/javascript')
        script.setAttribute('src', src)
        document.body.appendChild(script)
        window.onApiLoaded = function () {
            resolve()
        }

        const oW = document.write
        document.write = function (res) {
            let _srcArr = res.match('src\=\\"(.*)\\"')
            if (_srcArr[1]) {
                let _str = _srcArr[1]
                let _script = document.createElement('script')
                _script.setAttribute('type', 'text/javascript')
                _script.setAttribute('src', _str)
                document.body.appendChild(_script)
                _script.onerror = function () {
                    reject()
                    document.write = oW
                }
                _script.onload = function () {
                    resolve()
                    document.write = oW
                }
            }
        }
        script.onerror = function () {
            reject()
        }
    })
}
//全局 main.js 配置
import map from '@/lib/utils/map'
app.config.globalProperties.$map = map. //vue3
//使用
<template>
  <div class="map-mode-pool">
    <div class="map-container full" id="allmap"></div>
  </div>
</template>

<script setup>
import UtilsBMap from '@utils/AMap.js'
import {onMounted, ref,getCurrentInstance} from "vue";
const { proxy } = getCurrentInstance()

let map = ref(null)
let orderList = ref([])
onMounted (() => {
  getOrderList()
  initMap()
})

const initMap = () => {
  proxy.$map.loadMapJs().then(() => {
    loadMap()
  })
}
const loadMap = () => {
  console.log(44444444)
  let _lng = 108.87
  let _lat = 34.19
  UtilsBMap.initMap({ 'id' : 'allmap', 'lat' : _lat, 'lng' : _lng, 'zoom' :1 }).then((map) => {
    map.value = map
    UtilsBMap.setZoomAndCenter({ 'map' : map.value, 'latitude' : _lat, 'longitude' : _lng, 'zoom' :17  })
    loadMapMarker(map)
  })
}
const getOrderList = () => {
  proxy.$api.callAssets('order/list').then(({data}) => {
    console.log('data', data)
    orderList.value = data || {}
  })
}

const loadMapMarker = (map) => {
  let _markers = []
  let listData = [
    {
      'id':1,
      'balance_price':120,
      'order': {
        'gcj02_latitude':34.19,
        'gcj02_longitude':108.87
      },

    },
    {
      'id':2,
      'balance_price':140,
      'order': {
        'gcj02_latitude':34.193,
        'gcj02_longitude':108.8721
      },

    },
  ]
  orderList.value.map((item,index)=>{
    let _class = `merge-marker merge-marker-${item.id}`
    let _content = '<div class="' + _class + '"><span class="text">转</span><span class="price">¥' + item.balance_price + '</span></div>'
    UtilsBMap.addMarker({
      'map': map.value,
      'lng': item.gcj02_longitude,
      'lat': item.gcj02_latitude,
      'content': _content,
      'zIndex': 900 - index,
      'extData': item,
    }, function (marker) {
      _markers.push(marker)
      map.value.setFitView(_markers)
      marker.on('click', function (e) {
        let _extData = marker.getExtData()
        let elements = document.querySelectorAll('.merge-marker')
        elements.forEach((element) => {
          element.classList.remove('on');
        });
        let clickMark = document.querySelector(`.merge-marker-${_extData.id}`)
        clickMark.classList.add('on')
        proxy.$emit('getDetail',_extData.id)
      })
    })
  })
}
</script>

<style lang="scss">
.map-mode-pool {
  width: 100%;
  height: calc(100% - 70px);
  padding: 10px;
  .map-container{
    width: 100%;
    height: 100%;
  }
}
.merge-marker{
  height: 30px;
  background-color: #FF7326;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 0;
  padding: 4px 4px 4px 0;
  box-shadow: 3px 3px 5px 0px rgba(0, 0, 0, 0.3);
}
.merge-marker.on{
  background-color: #04BE02 !important;
}
.merge-marker span{
  text-align: center;

}
.merge-marker .text{
  width: 30px;
  color: #fff;
  background: transparent;
  font-size: 16px;
  border: 0;
}
.merge-marker.on span:first-child {
  background: #04BE02 !important;
}
.merge-marker .price{
  flex: 1;
  height: 100%;
  padding: 0 5px;
  line-height: 23px;
  background: white;
}
.merge-marker i{
  position: absolute;
  top: 29px;
  left: 8px;
  display: inline-block;
  width: 0;
  height: 0;
  border-top: 7px solid #FF7326;
  border-right: 7px dashed transparent;
  border-left: 7px dashed transparent;
}

.merge-marker.on i {
  border-top: 7px solid #04BE02 !important;
}

</style>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OpenLayers本身不支持直接加载百度地图,因为百度地图API使用了一些特殊的加密方式,无法直接在OpenLayers中实现。不过,您可以通过使用第三方插件或者自己编写代码的方式,在OpenLayers中加载百度地图。以下是两种常用的加载百度地图的方法: 1. 使用第三方插件 有一些第三方插件可以让OpenLayers支持加载百度地图,例如ol-ext(https://viglino.github.io/ol-ext/),这个插件可以让OpenLayers支持加载百度地图、高德地图等。 2. 自己编写代码 您也可以自己编写代码来实现在OpenLayers中加载百度地图。具体来说,您可以使用百度地图API获取瓦片图层,并将其添加到OpenLayers的地图上。代码实现可以参考以下示例: ``` // 创建百度地图图层 var baiduLayer = new ol.layer.Tile({ source: new ol.source.XYZ({ tileUrlFunction: function(tileCoord) { var x = tileCoord[1]; var y = tileCoord[2]; var z = tileCoord[0]; var url = "http://online{0-3}.map.bdimg.com/onlinelabel/?qt=tile&x=" + x + "&y=" + y + "&z=" + z + "&styles=pl&scaler=1"; return url; }, projection: 'EPSG:3857' }) }); // 创建OpenLayers地图对象 var map = new ol.Map({ target: 'map', layers: [baiduLayer], view: new ol.View({ center: ol.proj.fromLonLat([116.3975, 39.9087]), zoom: 10 }) }); ``` 需要注意的是,上述示例中的瓦片图层URL地址中的“online{0-3}”是百度地图提供的多个服务器地址,需要根据实际情况选择使用哪个地址。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值