NextJS - 谷歌地图动态改变标记的颜色

问题描述 投票:0回答:1

在我的 nextJS 应用程序中,我通过

@googlemaps/js-api-loader
包加载我的地图。我有一个要在地图上绘制的位置列表,同时在页面左侧有一个禁用的位置列表。

将鼠标悬停在列表中的某个位置上时,我想动态更改表示该位置的标记的颜色(类似于当前焦点在地图上的方式)。我怎样才能做到这一点?

这是我到目前为止的代码:

type MarkerObject = {
    id: number
    marker: google.maps.marker.AdvancedMarkerElement
}

export const MapComponent = ({ locations, currentFocusId }: MapProps) => {
    const [markers, setMarkers] = useState<MarkerObject[]>([])

    useEffect(() => {
        const initMap = async () => {
            const loader = new Loader({ apiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY! })
            const { Map } = (await loader.importLibrary('maps')) as google.maps.MapsLibrary
            // prettier-ignore
            const { AdvancedMarkerElement, PinElement } = (await loader.importLibrary('marker')) as google.maps.MarkerLibrary

            // create map
            const map = new Map(document.getElementById('map') as HTMLElement, {
                center: locations[0].position,
                zoom: 15,
                mapId: 'map',
            })

            // create markers
            for (const location of locations) {
                const pinBackground = new PinElement({
                    borderColor: 'black',
                    glyphColor: 'black',
                })

                const marker = new AdvancedMarkerElement({
                    map,
                    position: location.position,
                    content: pinBackground.element,
                })
                setMarkers((prev) => [...prev, { id: location.id, marker }])
            }
        }

        initMap()
    }, [])

useEffect(() => {
        if (!markers.length) return

        const focusMarker = markers.find((markerObject: MarkerObject) => markerObject.id === currentFocusId)
        if (!focusMarker) return

        // how can I change / replace the content or color of the marker to set it to blue?
    }, [currentFocusId])

    return <div id="map" style={{ width: '100vw', height: '100vh' }}></div>

我尝试过类似的事情

focusMarker.marker.content = new google.maps.marker.PinElement({
            background: 'blue',
            borderColor: 'black',
            glyphColor: 'black',
        })

但到目前为止还没有任何效果

javascript google-maps next.js google-maps-api-3 google-maps-advanced-marker-element
1个回答
0
投票

这是一个简单的例子。单击按钮将更改图钉背景颜色。

  1. 使用所需值创建
    PinElement
  2. 使用
    点符号
    更改 PinElement
  3. 属性
  4. 将修改后的
    PinElement
    内容应用到标记
    content
    属性

async function initMap() {

  // Request needed libraries.
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary(
    "marker",
  );

  const center = {
    lat: 0,
    lng: 0
  }

  const map = new Map(document.getElementById("map"), {
    center: center,
    zoom: 5,
    mapId: "4504f8b37365c3d0",
  });

  const pinBackground = new PinElement({
    background: 'red'
  })

  const marker = new AdvancedMarkerElement({
    map,
    position: center,
    content: pinBackground.element,
    title: "A marker using PinElement",
  });
  
  document.getElementById('changePin').addEventListener('click', function() {
    
    // Change background to "yellow"
    pinBackground.background = 'yellow'
    marker.content = pinBackground.element
  });
}

initMap();
#map {
  height: 140px;
  margin-bottom: 1em;
}
<div id="map"></div>
<button id="changePin">Change pin color</button>

<!-- prettier-ignore -->
<script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
        ({key: "AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk", v: "beta"});</script>

© www.soinside.com 2019 - 2024. All rights reserved.