vue3-baidu-map-gl

repository·main·Indexed 19 days ago

https://github.com/yue1123/vue3-baidu-map-gl

A Vue 3 component and hooks library that wraps the Baidu Maps JavaScript GL API. It provides ready-to-use components such as BAutoComplete, BContextMenu, BCity, BCopyright, BLocation, BNavigation3d, BPanoramaControl, BScale, and BZoom to simplify the integration of high-performance 3D map applications with full TypeScript support and automatic SDK management.

Tokens
21.3K
Snippets
56
Records
90
Agent score
66%

What's inside vue3-baidu-map-gl

  1. How BMap component lifecycle and WebGL cleanup works

    main

    The BMap component manages the lifecycle of the Baidu Map GL SDK.

    Important for WebGL users: When using WebGL rendering, it is critical to destroy the map instance to prevent 'too many WebGL context' warnings in the browser. The component automatically calls map.destroy() when the component is unmounted (onUnmounted).

    Initialization Flow:

    1. The component checks if it's running in a client environment (isClient).
    2. It asynchronously loads the Baidu Map GL script via getScriptAsync using the provided ak or apiUrl.
    3. Once the script is loaded, it initializes the BMapGL.Map instance.
    4. It applies initial props (center, zoom, etc.) and binds events.
    5. If plugins are provided, it initializes them and emits pluginReady.
    6. Finally, it emits initd to signal the map is ready for use.
  2. Use Vue-compatible utility types

    main

    The library provides several utility types to handle Vue's reactivity system seamlessly in configuration objects:

    • MaybeRef<T>: Accepts either a raw value T or a Vue Ref<T>.
    • MaybeRefOrGetter<T>: Accepts a raw value, a Ref<T>, or a getter function () => T.
    • DeepMaybeRef<T>: Recursively makes all nested properties of an object or array compatible with MaybeRef<T>. This is useful for passing complex configuration objects that might contain reactive properties.
    type MaybeRef<T> = T | Ref<T>
    
    type MaybeRefOrGetter<T> = MaybeRef<T> | (() => T)
    
    type DeepMaybeRef<T> = T extends Ref<infer V>
      ? MaybeRef<V>
      : T extends Array<any> | object
      ? { [K in keyof T]: DeepMaybeRef<T[K]> }
      : MaybeRef<T>
  3. Use the InfoWindow component

    main

    The InfoWindow component (exported as BInfoWindow) is used to display information overlays on a Baidu Map GL instance. It allows you to pass custom HTML content via a default slot.

    Note: The modelValue prop is deprecated. Use v-model:show for controlling visibility.

    <template>
      <BMapGLMap>
        <BMapGLInfoWindow 
          v-model:show="isInfoWindowVisible"
          :position="{ lng: 116.404, lat: 39.915 }"
          title="Location Info"
        >
          <div>
            <h3>Custom Content</h3>
            <p>This is inside the info window.</p>
          </div>
        </BMapGLInfoWindow>
      </BMapGLMap>
    </template>
    
    <script setup>
    import { ref } from 'vue'
    const isInfoWindowVisible = ref(true)
    </script>
  4. Install vue3-baidu-map-gl in a Vue 3 application

    main

    To use vue3-baidu-map-gl in your Vue 3 project, use the install method (or the default export) to register all components and global properties. You can pass an optional configuration object to set the Baidu Map Access Key (ak), API URL, and custom plugins.

    import { createApp } from 'vue'
    import Vue3BaiduMapGl from 'vue3-baidu-map-gl'
    
    const app = createApp(App)
    
    app.use(Vue3BaiduMapGl, {
      ak: 'YOUR_BAIDU_MAP_AK',
      apiUrl: 'YOUR_API_URL',
      // plugins and pluginsSourceLink can also be configured here
    })
    
    app.mount('#app')
  5. Configure Vue3BaiduMapGlOptions

    main

    When installing the plugin, you can provide a Vue3BaiduMapGlOptions object to configure global settings. These options are attached to the Vue application's globalProperties.

    export interface Vue3BaiduMapGlOptions {
      ak?: string           // Baidu Map Access Key
      apiUrl?: string       // Baidu Map API URL
      plugins?: UserPlugins // Custom user plugins
      pluginsSourceLink?: PluginsSourceLink // Link for plugin sources
    }
  6. Configure useViewAnimation options

    main

    When calling useViewAnimation, you can pass a UseViewAnimationOptions object to customize the animation behavior:

    OptionTypeDefaultDescription
    delaynumber0Delay before the animation starts (in ms).
    durationnumber1000Total duration of the animation (in ms).
    loopnumber | 'INFINITE'1Number of times to loop. Use 'INFINITE' for infinite loops.
    disableDraggingbooleantrueIf true, prevents the user from dragging the map while the animation is playing.
  7. Configure custom plugin source links

    main

    If you need to load a plugin from a specific URL instead of the default CDN, you can provide a customPluginSourceLink object to initPlugins. This object should be a partial mapping of plugin names to their source URLs.

    import { initPlugins, PluginsSourceLink } from 'vue3-baidu-map-gl';
    
    const customLinks: Partial<PluginsSourceLink> = {
      Mapvgl: 'https://my-private-cdn.com/mapvgl.min.js'
    };
    
    const plugins = await initPlugins(['Mapvgl'], customLinks);
  8. Configure useTrackAnimation options

    main

    When calling useTrackAnimation, you can provide a UseTrackAnimationOptions object to customize the animation behavior.

    OptionTypeDefaultDescription
    durationnumber10000Animation duration in milliseconds.
    delaynumber0Delay before the animation starts (ms).
    overallViewbooleantrueIf true, the map will automatically adjust its zoom/view to show the entire trajectory after the animation ends.
    tiltnumber55The map tilt angle during animation.
    zoomnumber'auto'The zoom level during animation. Use 'auto' to let the map adjust based on the trajectory.
  9. Configure BContextMenu props

    main

    The BContextMenu component accepts the following props:

    PropTypeDefaultDescription
    widthnumber100The width of the menu items.
    visiblebooleantrueWhether the context menu is currently active/visible on the map.
    menuItems(ContextMenuItem | ContextMenuSeparator)[][]An array of menu items or separators.
    onOpenCallback-Callback triggered when the menu opens.
    onCloseCallback-Callback triggered when the menu closes.
  10. Configure BPrism props

    main

    The BPrism component accepts the following props for configuration:

    PropTypeDefaultDescription
    pathPoint[] | string[]RequiredArray of node coordinates for the prism.
    altitudenumberRequiredThe height of the prism.
    isBoundarybooleanundefinedIf true, path is treated as an array of coordinate strings (typically for administrative boundaries).
    topFillColorstring'#fff'Color of the top surface.
    topFillOpacitynumber0.5Opacity of the top surface (0-1).
    sideFillColorstring'#fff'Color of the side surfaces.
    sideFillOpacitynumber0.8Opacity of the side surfaces (0-1).
    autoCenterbooleantrueAutomatically centers the map on the prism's bounds.
    enableMassClearbooleantrueWhether this overlay is included when calling map.clearOverlays.
    visiblebooleantrueControls the visibility of the prism.
    onClickCallback-Click event handler.
    onDblclickCallback-Double click event handler.
    onMouseoutCallback-Mouse out event handler.
    onMouseoverCallback-Mouse over event handler.
  11. Configure useBrowserLocation options

    main

    When calling useBrowserLocation, you can pass an options object to fine-tune the geolocation request behavior.

    OptionTypeDescription
    enableSDKLocationbooleanEnables SDK-assisted positioning. Useful for mobile web hybrid development.
    enableHighAccuracybooleanRequests the best possible accuracy from the browser (maps to browser geolocation parameters). Defaults to false.
    timeoutnumberTimeout in milliseconds. Defaults to 10000 (10s).
    maximumAgenumberAllows returning a cached position within this many milliseconds. If 0, always fetches the latest. Defaults to 600000 (10m).
    SDKLocationbooleanInternal mapping for enableSDKLocation.
    const options: UseBrowserLocationOptions = {
      enableSDKLocation: true,
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 60000,
    };
  12. Use MapDisplayOptions to control map elements

    main

    The displayOptions prop (of type MapDisplayOptions) allows you to fine-tune which visual elements are rendered on the map.

    Available options:

    • poi: Show/hide POI markers.
    • indoor: Show/hide indoor maps.
    • poiText: Show/hide POI text labels.
    • poiIcon: Show/hide POI icons.
    • overlay: Show/hide overlays.
    • layer: Show/hide overlay layers (not supported in Globe mode).
    • building: Show/hide 3D buildings (WebGL only).
    • street: Show/hide street networks (effective for Satellite and Globe modes).
    • skyColors: An array of two strings [string, string] to set sky colors.
    export interface MapDisplayOptions {
        poi?: boolean
        indoor?: boolean
        poiText?: boolean
        poiIcon?: boolean
        overlay?: boolean
        layer?: boolean
        building?: boolean
        street?: boolean
        skyColors?: [string, string]
    }