最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Google maps API Advanced Marker View set position? - Stack Overflow

programmeradmin5浏览0评论

I have create a marker using advancedMarkerView

const centerMarkerE = document.createElement("div");
let centerMarkerHtml = "<div class='center_marker'><img src='/images/front/pin.png' /></div>";
centerMarkerE.innerHTML = centerMarkerHtml;

centerMarker = new google.maps.marker.AdvancedMarkerView({
  map,
  position: initialLocation,
  content: centerMarkerE,
});

For normal marker I can use setPosition(initialLocation) but it not work for AdvancedMarkerView

How can I change the position of advance marker ?

I have create a marker using advancedMarkerView

const centerMarkerE = document.createElement("div");
let centerMarkerHtml = "<div class='center_marker'><img src='/images/front/pin.png' /></div>";
centerMarkerE.innerHTML = centerMarkerHtml;

centerMarker = new google.maps.marker.AdvancedMarkerView({
  map,
  position: initialLocation,
  content: centerMarkerE,
});

For normal marker I can use setPosition(initialLocation) but it not work for AdvancedMarkerView

How can I change the position of advance marker ?

Share Improve this question edited Aug 24, 2023 at 14:08 Yrll 2,5612 gold badges7 silver badges24 bronze badges asked Aug 22, 2023 at 8:34 Ryan WongRyan Wong 911 gold badge1 silver badge2 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13

Use Dot Notation instead of a setter method

AdvancedMarkerElementOptions interface have a position property. The documentation describes it this way:

Sets the AdvancedMarkerElement's position. An AdvancedMarkerElement may be constructed without a position, but will not be displayed until its position is provided - for example, by a user's actions or choices. An AdvancedMarkerElement's position can be provided by setting AdvancedMarkerElement.position if not provided at the construction.

So if you are instantiating an advanced marker like this:

const marker = new AdvancedMarkerElement({
  map,
  position: { lat: 14.535455012359806, lng: 120.98195420962453 },
});

You can change position within a click event listener like this:

btn.addEventListener("click", function(){
    // This is how to change marker location
    marker.position = {lat: 14.53546539778815,  lng: 120.98422872277972}
});

And this should work as expected.

Here's a sample snippet that you can play around with and check:

async function initMap() {
  // Request needed libraries.
  const btn = document.getElementById("change-location-btn");
    const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
  const map = new Map(document.getElementById("map"), {
    center: { lat: 14.535455012359806, lng: 120.98195420962453 },
    zoom: 16,
    mapId: "4504f8b37365c3d0",
  });
  const marker = new AdvancedMarkerElement({
    map,
    position: { lat: 14.535455012359806, lng: 120.98195420962453 },
  });
    
    // button to change location
btn.addEventListener("click", function(){
//      map.setCenter({lat: 14.53546539778815,  lng: 120.98422872277972})
    // This is how to change marker location
    marker.position = {lat: 14.53546539778815,  lng: 120.98422872277972}
});
    
}

initMap();
 
/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#map {
  height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}


[class$=api-load-alpha-banner] {
  display: none;
}
<html>
  <head>
    <title>Default Advanced Marker</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
        <button id="change-location-btn">Change Location</button>
    <div id="map">
    </div>

    <!-- 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./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>
  </body>
</html>

I hope this helps!

I came across this question as I was having issues updating a current marker's location using @googlemaps/react-wrapper.

@yrll's answer pointed me in the right direction, however, it is not enough to update the location. Updating the location every time the click was triggered would append a new Marker to the map.

To get it to work as expected, I had to change how I defined the AdvancedMarkerElement. I do not pass the map object to the constructor.

  useEffect(() => {
    const pinBackground = new google.maps.marker.PinElement({
      background: "#FBBC04",
    });
    const marker = new google.maps.marker.AdvancedMarkerElement({
      content: pinBackground.element,
    });
    setMarker(marker);
  }, []);

Instead, I pass in the map to the marker on the first change. Then it works as expected.

  const updateMarker = useCallback(
    (location: google.maps.LatLng) => {
      if (marker) {
        if (!marker.map) {
          marker.map = map;
        }
        if (marker.position !== location) marker.position = location;
      }
    },
    [map, marker]
  );
发布评论

评论列表(0)

  1. 暂无评论