Я пытаюсь перенести свои пользовательские маркеры карты в новую расширенную библиотеку маркеров, кажется, параметры анимации больше недоступны, это выдает следующую ошибку:
Неизвестное свойство «анимация» AdvancedMarkerElement
Я проверил документацию и обнаружил, что параметры анимации все еще присутствуют, но ничего не упоминается о том, как перенести параметр анимации.
документация по маркерам Google
newMarker = new google.maps.marker.AdvancedMarkerElement({
position: markerOpposto,
map: map,
content: imageIcon,
title: "New position",
animation: google.maps.Animation.BOUNCE
})
Первое, что нам нужно понять о Advanced Marker, это то, что он больше не является объектом MVC, в отличие от Legacy Markers. Знаки Animation constants
(BOUNCE
и DROP
), существовавшие на маркере наследия, больше не доступны.
Это связано с тем, что, согласно документации , класс Advanced Marker теперь расширяется HTMLElement
. Это означает, что для анимации расширенного маркера вам теперь следует использовать CSS-анимацию, как показано в примере расширенного маркера здесь: https://developers.google.com/maps/documentation/javascript/examples/ продвинутые маркеры-анимация
С учетом вышесказанного, чтобы воспроизвести похожую анимацию отскока, вам сначала нужно определить класс .bounce
(вы можете назвать его как хотите) внутри вашего CSS, используя ключевые кадры и преобразование:
.bounce {
animation: bounce 2s infinite;
-webkit-animation: bounce 2s infinite;
-moz-animation: bounce 2s infinite;
-o-animation: bounce 2s infinite;
}
@-webkit-keyframes bounce {
0%, 20%, 50%, 80%, 100% {-webkit-transform: translateY(0);}
40% {-webkit-transform: translateY(-30px);}
60% {-webkit-transform: translateY(-15px);}
}
@-moz-keyframes bounce {
0%, 20%, 50%, 80%, 100% {-moz-transform: translateY(0);}
40% {-moz-transform: translateY(-30px);}
60% {-moz-transform: translateY(-15px);}
}
@-o-keyframes bounce {
0%, 20%, 50%, 80%, 100% {-o-transform: translateY(0);}
40% {-o-transform: translateY(-30px);}
60% {-o-transform: translateY(-15px);}
}
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {transform: translateY(0);}
40% {transform: translateY(-30px);}
60% {transform: translateY(-15px);}
}
Затем внутри функции инициализации карты вы можете просто добавить класс .bounce
к элементу маркера, используя этот код:
marker.content.classList.add("bounce")
Тогда анимация должна работать.
Вот фрагмент доказательства концепции, который вы можете проверить:
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
async function initMap() {
// Request needed libraries.
const { Map } = await google.maps.importLibrary("maps");
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
// initialize the map
const map = new Map(document.getElementById("map"), {
center: { lat: 37.4239163, lng: -122.0947209 },
zoom: 14,
mapId: "4504f8b37365c3d0",
});
// initialize the marker
const marker = new AdvancedMarkerElement({
map,
position: { lat: 37.4239163, lng: -122.0947209 },
});
// add the class "bounce" for your css configuration to apply
marker.content.classList.add("bounce")
}
initMap();
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
/*
* 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;
}
/* Define the bounce animation configuration here */
.bounce {
animation: bounce 2s infinite;
-webkit-animation: bounce 2s infinite;
-moz-animation: bounce 2s infinite;
-o-animation: bounce 2s infinite;
}
@-webkit-keyframes bounce {
0%, 20%, 50%, 80%, 100% {-webkit-transform: translateY(0);}
40% {-webkit-transform: translateY(-30px);}
60% {-webkit-transform: translateY(-15px);}
}
@-moz-keyframes bounce {
0%, 20%, 50%, 80%, 100% {-moz-transform: translateY(0);}
40% {-moz-transform: translateY(-30px);}
60% {-moz-transform: translateY(-15px);}
}
@-o-keyframes bounce {
0%, 20%, 50%, 80%, 100% {-o-transform: translateY(0);}
40% {-o-transform: translateY(-30px);}
60% {-o-transform: translateY(-15px);}
}
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {transform: translateY(0);}
40% {transform: translateY(-30px);}
60% {transform: translateY(-15px);}
}
<!doctype html>
<!--
@license
Copyright 2019 Google LLC. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
-->
<html>
<head>
<title>Default Advanced Marker</title>
<script src = "https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<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.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: "weekly"});</script>
</body>
</html>
Упс, спасибо, что указали на это! Я просто скопировал и вставил код CSS на какой-то веб-сайт и не заморачивался, что делает это объявление, лол.
спасибо @Yrll за рабочий пример! AFAIK (!), на данный момент мы вроде как спокойно можем опускать варианты поставщиков для объявлений
@-…-keyframes
. См. также caniuse.com/?search=keyframes. Так что, если вы предпочитаете немного более краткий код, а не полную поддержку браузеров старой школы, смело используйте только раздел@keyframes bounce
.