[Tian Map] VUE3 encapsulates some function hooks of Tian Map useTdtMap.js

It is only packaged based on personal habits and is for reference only.

Tianditu API address: http://lbs.tianditu.gov.cn/api/js4.0/class.html

In addition to the sky map, this hook also needs to introduce the open source library Image Overlay! ! ! Open source library address: http://lbs.tianditu.gov.cn/api/js4.0/opensource/source.html

The detailed description of each method is reflected in the code. First, create a hook-useTdtMap.js

/**
 * useTdtMap (Tian Map hooks)
 *params:
 * id: the html tag id bound to Tiantu, which is unique
 */
import { createVNode, render } from 'vue'

export const useTdtMap = (id) => {
let map = null // map object

// Map initialization, please configure the map initialization operation according to your personal situation.
const mapInit = () => {
map = new T.Map(id)
//Set the map center point coordinates and map level
map.centerAndZoom(new T.LngLat(116.40769, 39.89945), 12)
//Create object
map.disableDoubleClickZoom() // Disable double-clicking to enlarge the map
//Set the background color
map.setStyle('indigo')
document.getElementsByClassName('tdt-control-copyright tdt-control')[0].style.display = 'none' // Remove the Tiantu logo
return Promise.resolve() // Callback map initialization completed
}

    /**
     * setMapCenter (map pan)
     * params:
     * coordinate: latitude and longitude of center point
     * Format: 'lng,lat'
     * Example: '116.40769,39.89945'
     * The following coordinate format is consistent with this format
     */
const setMapCenter = (coordinate) => {
let lng = coordinate.split(',')[0]
let lat = coordinate.split(',')[1]
map.panTo(new T.LngLat(lng, lat))
}

// Map zoom coordinate: Same as above zoom: Scale level
const setMapScale = (coordinate, zoom) => {
let lng = coordinate.split(',')[0]
let lat = coordinate.split(',')[1]
map.centerAndZoom(new T.LngLat(lng, lat), zoom)
}

//Map display range coordinate1: range point 1 coordinate2: range point 2
const setMapBounds = (coordinate1, coordinate2) => {
let lng1 = coordinate1.split(',')[0]
let lat1 = coordinate1.split(',')[1]
let lng2 = coordinate2.split(',')[0]
let lat2 = coordinate2.split(',')[1]
map.setMaxBounds(new T.LngLatBounds(new T.LngLat(lng1, lat1), new T.LngLat(lng2, lat2)))
}

// Map settings display level
const setZoomLevels = (minLevels = 1, maxLevels = 18) => {
map.setMinZoom(minLevels)
map.setMaxZoom(maxLevels)
}

/**
* Add image overlay class
*params:
* coordinate1: latitude and longitude format: 'lng,lat'
* coordinate2: latitude and longitude format: 'lng,lat'
* imgUrl: point display icon
* option: image overlay attribute, { opacity: image transparency, alt: if the image cannot be displayed, the browser will display alternative text }
*/
const addMapImgOverLay = (coordinate1, coordinate2, imgUrl, option = {}) => {
let lng1 = coordinate1.split(',')[0]
let lat1 = coordinate1.split(',')[1]
let lng2 = coordinate2.split(',')[0]
let lat2 = coordinate2.split(',')[1]
let bd = new T.LngLatBounds(new T.LngLat(lng1, lat1), new T.LngLat(lng2, lat2))
let img = new T.ImageOverlay(imgUrl, bd, option)
map.addOverLay(img)
// return img
}

/**
* Add a custom point to the map and return the point object
*params:
* coordinate: latitude and longitude format: 'lng,lat'
* iconUrl: point display icon
* clickEvent: monitor click event callback
* iconOptions: Tiantu ICON icon configuration
\t *   Format:{
     * iconSize: '30,30', icon size, optional configuration
     * iconAnchor: '15,30' icon offset, optional configuration
     * }
*/
const addMapMarker = (
coordinate,
iconUrl = '*',
clickEvent = null,
iconOptions = {}
) => {
let marker = getMapMarkerObj(coordinate, iconUrl, iconOptions)
if (clickEvent) {
marker.addEventListener('click', clickEvent)
}
addMapOverLay(marker)
return marker
}

//Generate point label object
const getMapMarkerObj = (coordinate, iconUrl, iconOptions) => {
let lng = coordinate.split(',')[0]
let lat = coordinate.split(',')[1]
const option = {
iconSize: iconOptions.iconSize || '30,30',
iconAnchor: iconOptions.iconAnchor || '15,30'
}
//Add point icon
let icon = new T.Icon({
iconUrl: iconUrl,
iconSize: new T.Point(option.iconSize.split(',')[0], option.iconSize.split(',')[1]),
iconAnchor: new T.Point(option.iconAnchor.split(',')[0], option.iconAnchor.split(',')[1])
})
let marker = new T.Marker(new T.LngLat(lng, lat), { icon: icon })
return marker
}

/**
* Add a custom line to the map and return the line object
* params:
* coordinateList: Array of longitude and latitude of each point of the line Format: [{ lng: 'lng', lat: 'lat' }]
* polylineOption: Line configuration item, refer to Tianmap
* clickEvent: monitor click event callback
*/
const addMapLine = (coordinateList, polylineOption = null, clickEvent = null) => {
let points = coordinateList.map((item) => {
return new T.LngLat(item.lng, item.lat)
})
let marker = new T.Polyline(points, polylineOption)
if (clickEvent) {
marker.addEventListener('click', clickEvent)
}
addMapOverLay(marker)
return marker
}

/**
* Add a custom polygon to the map and return the line object
*params:
* coordinateList: Array of longitude and latitude of each point on the surface Format: [[{ lng: 'lng', lat: 'lat' }], [{ lng: 'lng', lat: 'lat' }]]
* Format description: handle the inner ring situation. The outer ring position is defined counterclockwise. The inner ring position value is clockwise defined.
* polylineOption: polyline configuration item, refer to Tianmap
* clickEvent: monitor click event callback
*/
const addMapPolygon = (coordinateList, polygonOption = null, clickEvent = null) => {
let polygon = coordinateList.map((item) => {
return item.map((pointItem) => {
return new T.LngLat(pointItem.lng, pointItem.lat)
})
})
let marker = new T.Polygon(polygon, polygonOption)
if (clickEvent) {
marker.addEventListener('click', clickEvent)
}
addMapOverLay(marker)
return marker
}

/**
* Add a custom window to the map and return the window object
*params:
* coordinate: information window latitude and longitude format: 'lng,lat'
* infoWindowOption: information window configuration item
* template: custom template component
* params: Pass in component custom parameters
* clickEvent: monitor click event callback
*/
const addMapInfoWindow = (coordinate, infoWindowOption, template, params, clickEvent = null) => {
//Create virtual node and pass parameters
const infoWindowContent = getTemplateNode(template, params)
//Listen to the component's custom handleClick event
clickEvent & amp; & amp; infoWindowContent.el.addEventListener('click', clickEvent)
// Create a sky map information window infoWindowContent.el: test template dom
let infoWindow = getInfoWindowObj(infoWindowContent.el, coordinate, infoWindowOption)
// Map add information window
addMapOverLay(infoWindow)
return infoWindow
}

/**
* Generate a template node and pass parameters
*params:
* template: Custom template component
* params: Pass in component custom parameters
*/
const getTemplateNode = (template, params) => {
//Create virtual node and pass parameters
const infoWindowContent = createVNode(template, params)
let node = document.createElement('div') // Create a div node
render(infoWindowContent, node) //The instance component is mounted on the node node
return infoWindowContent
}

//Generate information window object
const getInfoWindowObj = (el, coordinate, infoWindowOption) => {
let lng = coordinate.split(',')[0]
let lat = coordinate.split(',')[1]
let infoWindow = new T.InfoWindow(el, infoWindowOption)
//Set the latitude and longitude of the information window
infoWindow.setLngLat(new T.LngLat(lng, lat))
return infoWindow
}

// Add a cover to the map obj: cover object
const addMapOverLay = (obj) => {
map.addOverLay(obj)
}

// Remove the cover from the map obj: cover object
const removeMapOverLay = (obj) => {
map.removeOverLay(obj)
}

// Map removes all overlays
const removeMapAllOverLay = () => {
map.clearOverLays()
}

return {
mapInit,
setMapCenter,
setMapScale,
setMapBounds,
setZoomLevels,
addMapImgOverLay,
addMapMarker,
addMapLine,
addMapPolygon,
addMapInfoWindow,
addMapOverLay,
removeMapOverLay,
removeMapAllOverLay
}
}

Introduce the sky map hooks and initialize the map. The following are part of the key codes:

<template>
    <div id="TdtMap" class="map-div"></div>
</template>
<script setup>
    import { useTdtMap } from '@/hooks/useTdtMap'
    //Introduce
const {
mapInit,
renderArea,
setMapCenter,
setMapScale,
setMapBounds,
setZoomLevels,
addMapImgOverLay,
addMapMarker,
addMapLine,
addMapPolygon,
addMapInfoWindow,
addMapOverLay,
removeMapOverLay,
removeMapAllOverLay
} = useTdtMap('TdtMap')
    //Initialize the map
    onMounted(() => {
        mapInit().then(() => {
            // Callback operation after map initialization is completed
        })
    })
</script>
<style scoped>
    .map-div {
        width: 100vw;
        height: 100vh;
    }
</style>

setMapCenter: Manually set map pan example:

setMapCenter('116.40769,39.89945')

setMapScale: Manually set the map center point and scale level example:

setMapScale('104.06595,30.57054', 13) // Set map zoom

setMapBounds: Manually set the map display range Example:

setMapBounds('103.90114,30.49365', '104.23073,30.64736') // Set the map display range

setZoomLevels: Manually set map display levels Example:

setZoomLevels(12, 18) //Set map levels

addMapImgOverLay: Add a map image overlay Example:

import testImg from '@/assets/image/test.png'
addMapImgOverLay(
    '103.8687,30.72825',
    '104.27167,30.38782',
    testImg,
    {
opacity: 100,
alt: ''
    }
)

addMapMarker: Add a custom point and return the point object. Example:

import testIcon from '@/assets/image/test.png'
const marker = addMapMarker(
                    '116.40769,39.89945',
                    testIcon,
                    () => {},
                    {
                        iconSize: '30,30',
                        iconAnchor: '15,30'
                    }
                )

addMapLine: Add a custom line and return the line object Example:

const coordinateList = [
    {
        lng: '116.40769',
        lat: '39.89945'
    },
    {
        lng: '116.50769',
        lat: '39.99945'
    },
    {
        lng: '116.60769',
        lat: '39.79945'
    },
    {
        lng: '116.70769',
        lat: '39.69945'
    },
    {
        lng: '116.80769',
        lat: '39.59945'
    }
]

//Default line configuration
const marker = addMapLine(coordinateList)

addMapPolygon: Add a custom polygon and return the polygon object. Example:

// Four corners of the mask layer China four-corner coordinates External layer
const smegmaPointList = [
{
lng: '73.0',
lat: '59.0'
},
{
lng: '73.0',
lat: '3.0'
},
{
lng: '136.0',
lat: '3.0'
},
{
lng: '136.0',
lat: '59.0'
},
{
lng: '73.0',
lat: '59.0'
}
]
// geographic range
const mapCoordinateData = [
{
lng: '104.0325',
lat: '30.56888'
},
{
lng: '104.04353',
lat: '30.56795'
},
{
lng: '104.04375',
lat: '30.53942'
},
{
lng: '104.02315',
lat: '30.53931'
},
{
lng: '104.02164',
lat: '30.54504'
},
{
lng: '104.02542',
lat: '30.55657'
},
{
lng: '104.03053',
lat: '30.56278'
},
{
lng: '104.0325',
lat: '30.56888'
}
]
//Normal screen example
const marker = addMapPolygon([smegmaPointList])
// Draw an inner circle example and configure related information
const marker = addMapPolygon(
                    [smegmaPointList, mapCoordinateData],
                    {
color: 'black',
                    weight: 3,
                    opacity: 0.2,
fillColor: '#0c2940', // Mask color
fillOpacity: 0.7 // transparency
                    },
                    () => {}
                )

addMapInfoWindow: Add a custom information window and return the window object Example:

// Custom module test @/components/test/index.vue
<template>
    <div>{<!-- -->{ title }}</div>
<template>

<script>
    defineProps({
        title: {
            type: String,
            default: ''
        }
    })
</scropt>

//Customized information window key code
import TestTemplate from '@/components/test/index.vue'

const infoWindowOption = {
    closeButton: false, //Close the sky and map pop-up box by default to close the icon
    offset: new T.Point(0, -15)
}
const infoWindow = addMapInfoWindow('116.40769,39.89945', infoWindowOption, TestTemplate, {
title: 'Test text' })

addMapOverLay: Add overlay example:

addMapOverLay(marker) //marker is the same as the above example

addMapOverLay: remove overlay example:

removeMapOverLay(marker) //marker is the same as the above example

removeMapAllOverLay: Remove all overlays on the sky map Example:

removeMapAllOverLay()