Markers | Maps JavaScript API - Google Developers

文章推薦指數: 80 %
投票人數:10人

// In the following example, markers appear when the user clicks on the map. // Each marker is labeled with a single alphabetical character. ... ); // This event ... Google MapsPlatform Overview Products Pricing Documentation GetStarted GetStartedwithGoogleMapsPlatform APIPicker Billing&Pricing Reporting&Monitoring MapIDs FAQ SupportandResources IncidentManagement Maps MapsJavaScriptAPI MapsSDKforAndroid MapsSDKforiOS MapsStaticAPI StreetViewStaticAPI MapsEmbedAPI MapsURLs MapsElevationAPI Routes DirectionsAPI DistanceMatrixAPI RoadsAPI Solutions IndustrySolutions GamingServices TransportationandLogistics Places PlacesAPI PlacesSDKforAndroid PlacesSDKforiOS PlacesLibrary,MapsJavaScriptAPI GeocodingAPI GeolocationAPI TimeZoneAPI AdditionalResources APISecurityBestPractices MapCoverageDetails OptimizationGuide MobileOSandsoftwaresupport Deprecations AssetTrackingPlan RootCAMigrationFAQ URLEncoding WordPressUsers Blog Community StackOverflow GitHub YouTube Discord Twitter IssueTracker Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어 Signin Web MapsJavaScriptAPI GetStarted Contactsales Guides Reference Samples Support Google MapsPlatform Overview Products Pricing Documentation More Guides Reference Samples Support Blog Community More MapsJavaScriptAPI Overview SetupinCloudConsole UsingAPIKeys Tutorials Alltutorials Addamarkertoyourmap Clustermarkers Real-timecollaborativemapping Showcurrentlocation Usedatawithyourmap DisplayingKMLImportingJSONdataVisualizingJSONdataCombiningJSONdata AddingaMapandMarkerstoaReactApplication Concepts Allconcepts Maptypes Mapandtilecoordinates Localizingthemap Versioning URLparameters Bestpractices UsingTypeScript Promises Managemarkerlabelcollisions Customizeamap CustomizewithCloudbasedmapsstyling CustomizewithJSONstyling JSONstylingoverviewJSONstylereference CustomLegends Interactwiththemap Controls Events Controlzoomandpan Drawonthemap Overview Markers Custommarkers Infowindows Shapes Symbols WebGLFeatures OverviewVectorMapsTiltandRotationWebGLOverlayView Deck.gldatavisualizations Groundoverlays Customoverlays Displaydata Overview Data-drivenstyling(Preview) OverviewGetstartedStyleaboundarypolygonMakeachoroplethmapHandleclickeventsUsetheRegionLookupAPIUsetheRegionLookupAPIwithGoogleSheetsUseGeocodingandPlacesAPIswithData-drivenstylingGoogleboundariescoverage Datalayer Heatmap KMLandGeoRSS Traffic,Transit,andBicyclingLayers Services Directions DistanceMatrix Elevation Geocoding MaximumZoomImagery StreetView Libraries Overview DrawingLibrary GeometryLibrary LocalContextLibrary(Beta) OverviewGetStartedSettingLocalContextandMapOptionsHandlingEventsandUserInteractionRefreshingSearchPropertiesStylingtheLocalContextMapViewSupportedPlaceTypesMigratingaMaptoLocalContextMapView PlacesLibrary PlaceAutocomplete VisualizationLibrary OpenSourceLibraries MoreGuides ContentSecurityPolicyGuide GoogleLoaderMigrationGuide PlaceFieldMigration(open_now,utc_offset) PlaceDataFields PlaceIcons PlaceIDs PlaceTypes Upgradingfromv2tov3 PoliciesandTerms Usageandbilling Reportingandmonitoring Termsofservice OtherAPIs MapsStaticAPI StreetViewStaticAPI MapsEmbedAPI MapsURLs GetStarted GetStartedwithGoogleMapsPlatform APIPicker Billing&Pricing Reporting&Monitoring MapIDs FAQ SupportandResources IncidentManagement Maps MapsJavaScriptAPI MapsSDKforAndroid MapsSDKforiOS MapsStaticAPI StreetViewStaticAPI MapsEmbedAPI MapsURLs MapsElevationAPI Routes DirectionsAPI DistanceMatrixAPI RoadsAPI Solutions IndustrySolutions GamingServices TransportationandLogistics Places PlacesAPI PlacesSDKforAndroid PlacesSDKforiOS PlacesLibrary,MapsJavaScriptAPI GeocodingAPI GeolocationAPI TimeZoneAPI AdditionalResources APISecurityBestPractices MapCoverageDetails OptimizationGuide MobileOSandsoftwaresupport Deprecations AssetTrackingPlan RootCAMigrationFAQ URLEncoding WordPressUsers StackOverflow GitHub YouTube Discord Twitter IssueTracker Home Products GoogleMapsPlatform Documentation Web MapsJavaScriptAPI Sendfeedback Markers Selectplatform: Android iOS JavaScript Introduction Amarkeridentifiesalocationonamap.Bydefault,amarkerusesa standardimage.Markerscandisplaycustomimages,inwhichcasetheyare usuallyreferredtoas"icons."Markersandiconsareobjectsoftype Marker.Youcansetacustomiconwithinthemarker'sconstructor,orby callingsetIcon()onthemarker.Seemoreabout customizingthemarkerimage. Broadlyspeaking,markersareatypeofoverlay.Forinformationonother typesofoverlay,see Drawingonthemap. Markersaredesignedtobeinteractive.Forexample,bydefaultthey receive'click'events,soyoucanaddaneventlistenerto bringupan infowindow displayingcustominformation.Youcanallowuserstomoveamarkeronthe mapbysettingthemarker'sdraggablepropertyto true.Formoreinformationaboutdraggablemarkers,see below. Addamarker The google.maps.Marker constructortakesasingleMarkeroptionsobject literal,specifyingtheinitialpropertiesofthemarker. Thefollowingfieldsareparticularlyimportantandcommonlysetwhen constructingamarker: position(required)specifiesa LatLngidentifyingtheinitiallocationofthemarker.One wayofretrievingaLatLngisbyusingthe Geocodingservice. map(optional)specifiestheMaponwhichto placethemarker.Ifyoudonotspecifythemaponconstructionofthe marker,themarkeriscreatedbutisnotattachedto(ordisplayedon) themap.Youmayaddthemarkerlaterbycallingthemarker's setMap()method. ThefollowingexampleaddsasimplemarkertoamapatUluru,inthe centerofAustralia: TypeScript functioninitMap():void{ constmyLatLng={lat:-25.363,lng:131.044}; constmap=newgoogle.maps.Map( document.getElementById("map")asHTMLElement, { zoom:4, center:myLatLng, } ); newgoogle.maps.Marker({ position:myLatLng, map, title:"HelloWorld!", }); } declareglobal{ interfaceWindow{ initMap:()=>void; } } window.initMap=initMap;index.ts Note:ReadtheguideonusingTypeScriptandGoogleMaps. JavaScript functioninitMap(){ constmyLatLng={lat:-25.363,lng:131.044}; constmap=newgoogle.maps.Map(document.getElementById("map"),{ zoom:4, center:myLatLng, }); newgoogle.maps.Marker({ position:myLatLng, map, title:"HelloWorld!", }); } window.initMap=initMap;index.js Note:TheJavaScriptiscompiledfromtheTypeScriptsnippet. Viewexample TrySample Stackblitz.com CodeSandbox.io JSFiddle.net GitPod.io GoogleCloudShell Intheaboveexample,themarkerisplacedonthemapatconstructionof themarkerusingthemappropertyinthemarkeroptions. Alternatively,youcanaddthemarkertothemapdirectlybyusingthe marker'ssetMap()method,asshownintheexamplebelow: varmyLatlng=newgoogle.maps.LatLng(-25.363882,131.044922); varmapOptions={ zoom:4, center:myLatlng } varmap=newgoogle.maps.Map(document.getElementById("map"),mapOptions); varmarker=newgoogle.maps.Marker({ position:myLatlng, title:"HelloWorld!" }); //Toaddthemarkertothemap,callsetMap(); marker.setMap(map); Themarker'stitlewillappearasatooltip. IfyoudonotwishtopassanyMarkeroptionsinthe marker'sconstructor,insteadpassanemptyobject{}inthe lastargumentoftheconstructor. Viewexample Removeamarker Toremoveamarkerfromthemap,callthesetMap()method passingnullastheargument. marker.setMap(null); Notethattheabovemethoddoesnotdeletethemarker.Itremovesthe markerfromthemap.Ifinsteadyouwishtodeletethemarker,youshould removeitfromthemap,andthensetthemarkeritselfto null. Ifyouwishtomanageasetofmarkers,youshouldcreateanarraytohold themarkers.Usingthisarray,youcanthencallsetMap()on eachmarkerinthearrayinturnwhenyouneedtoremovethemarkers.You candeletethemarkersbyremovingthemfromthemapandthensettingthe array'slengthto0,whichremovesall referencestothemarkers. Viewexample Customizeamarkerimage Youcancustomizethevisualappearanceofmarkersbyspecifyingan imagefileor vector-basedicontodisplayinsteadofthedefault GoogleMapspushpinicon.Youcanaddtextwitha markerlabel,anduse complexiconstodefineclickableregions, andsetthestackorderofmarkers. Markerswithimageicons Inthemostbasiccase,aniconcanspecifyanimagetouseinsteadofthe defaultGoogleMapspushpinicon.Tospecifysuchanicon,setthe marker'siconpropertytotheURLofanimage.TheMapsJavaScriptAPIwillsizetheiconautomatically. TypeScript //ThisexampleaddsamarkertoindicatethepositionofBondiBeachinSydney, //Australia. functioninitMap():void{ constmap=newgoogle.maps.Map( document.getElementById("map")asHTMLElement, { zoom:4, center:{lat:-33,lng:151}, } ); constimage= "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png"; constbeachMarker=newgoogle.maps.Marker({ position:{lat:-33.89,lng:151.274}, map, icon:image, }); } declareglobal{ interfaceWindow{ initMap:()=>void; } } window.initMap=initMap;index.ts Note:ReadtheguideonusingTypeScriptandGoogleMaps. JavaScript //ThisexampleaddsamarkertoindicatethepositionofBondiBeachinSydney, //Australia. functioninitMap(){ constmap=newgoogle.maps.Map(document.getElementById("map"),{ zoom:4, center:{lat:-33,lng:151}, }); constimage= "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png"; constbeachMarker=newgoogle.maps.Marker({ position:{lat:-33.89,lng:151.274}, map, icon:image, }); } window.initMap=initMap;index.js Note:TheJavaScriptiscompiledfromtheTypeScriptsnippet. Viewexample TrySample Stackblitz.com CodeSandbox.io JSFiddle.net GitPod.io GoogleCloudShell Markerswithvector-basedicons YoucanusecustomSVGvectorpathstodefinethevisualappearanceof markers.Todothis,passaSymbolobjectliteralwiththe desiredpathtothemarker'siconproperty.Youcandefinea custompathusing SVGpathnotation,oruseoneofthepredefinedpathsin google.maps.SymbolPath.Theanchorpropertyisrequiredinorderforthemarkerto rendercorrectlywhenthezoomlevelchanges.Learnmoreabout usingSymbolstocreatevector-basedicons formarkers(andpolylines). TypeScript //ThisexampleusesSVGpathnotationtoaddavector-basedsymbol //astheiconforamarker.Theresultingiconisamarker-shaped //symbolwithabluefillandnoborder. functioninitMap():void{ constcenter=newgoogle.maps.LatLng(-33.712451,150.311823); constmap=newgoogle.maps.Map( document.getElementById("map")asHTMLElement, { zoom:9, center:center, } ); constsvgMarker={ path:"M10.45314.016l6.563-6.609-1.406-1.406-5.1565.203-2.063-2.109-1.4061.406zM122.016q2.90604.9452.039t2.0394.945q01.453-0.7273.328t-1.7583.516-2.0393.070-1.7112.273l-0.750.797q-0.281-0.328-0.75-0.867t-1.688-2.156-2.133-3.141-1.664-3.445-0.75-3.375q0-2.9062.039-4.945t4.945-2.039z", fillColor:"blue", fillOpacity:0.6, strokeWeight:0, rotation:0, scale:2, anchor:newgoogle.maps.Point(15,30), }; newgoogle.maps.Marker({ position:map.getCenter(), icon:svgMarker, map:map, }); } declareglobal{ interfaceWindow{ initMap:()=>void; } } window.initMap=initMap;index.ts Note:ReadtheguideonusingTypeScriptandGoogleMaps. JavaScript //ThisexampleusesSVGpathnotationtoaddavector-basedsymbol //astheiconforamarker.Theresultingiconisamarker-shaped //symbolwithabluefillandnoborder. functioninitMap(){ constcenter=newgoogle.maps.LatLng(-33.712451,150.311823); constmap=newgoogle.maps.Map(document.getElementById("map"),{ zoom:9, center:center, }); constsvgMarker={ path:"M10.45314.016l6.563-6.609-1.406-1.406-5.1565.203-2.063-2.109-1.4061.406zM122.016q2.90604.9452.039t2.0394.945q01.453-0.7273.328t-1.7583.516-2.0393.070-1.7112.273l-0.750.797q-0.281-0.328-0.75-0.867t-1.688-2.156-2.133-3.141-1.664-3.445-0.75-3.375q0-2.9062.039-4.945t4.945-2.039z", fillColor:"blue", fillOpacity:0.6, strokeWeight:0, rotation:0, scale:2, anchor:newgoogle.maps.Point(15,30), }; newgoogle.maps.Marker({ position:map.getCenter(), icon:svgMarker, map:map, }); } window.initMap=initMap;index.js Note:TheJavaScriptiscompiledfromtheTypeScriptsnippet. Viewexample TrySample Stackblitz.com CodeSandbox.io JSFiddle.net GitPod.io GoogleCloudShell Markerlabels Amarkerlabelisaletterornumberthatappearsinsideamarker.The markerimageinthissectiondisplaysamarkerlabelwiththeletter'B' onit.Youcanspecifyamarkerlabelaseitherastringora MarkerLabel objectthatincludesastringandotherlabelproperties. Whencreatingamarker,youcanspecifyalabelpropertyin the MarkerOptions object.Alternatively,youcancallsetLabel()onthe Marker objecttosetthelabelonanexistingmarker. Thefollowingexampledisplayslabeledmarkerswhentheuserclicksonthe map: TypeScript //Inthefollowingexample,markersappearwhentheuserclicksonthemap. //Eachmarkerislabeledwithasinglealphabeticalcharacter. constlabels="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; letlabelIndex=0; functioninitMap():void{ constbangalore={lat:12.97,lng:77.59}; constmap=newgoogle.maps.Map( document.getElementById("map")asHTMLElement, { zoom:12, center:bangalore, } ); //ThiseventlistenercallsaddMarker()whenthemapisclicked. google.maps.event.addListener(map,"click",(event)=>{ addMarker(event.latLng,map); }); //Addamarkeratthecenterofthemap. addMarker(bangalore,map); } //Addsamarkertothemap. functionaddMarker(location:google.maps.LatLngLiteral,map:google.maps.Map){ //Addthemarkerattheclickedlocation,andaddthenext-availablelabel //fromthearrayofalphabeticalcharacters. newgoogle.maps.Marker({ position:location, label:labels[labelIndex++%labels.length], map:map, }); } declareglobal{ interfaceWindow{ initMap:()=>void; } } window.initMap=initMap;index.ts Note:ReadtheguideonusingTypeScriptandGoogleMaps. JavaScript //Inthefollowingexample,markersappearwhentheuserclicksonthemap. //Eachmarkerislabeledwithasinglealphabeticalcharacter. constlabels="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; letlabelIndex=0; functioninitMap(){ constbangalore={lat:12.97,lng:77.59}; constmap=newgoogle.maps.Map(document.getElementById("map"),{ zoom:12, center:bangalore, }); //ThiseventlistenercallsaddMarker()whenthemapisclicked. google.maps.event.addListener(map,"click",(event)=>{ addMarker(event.latLng,map); }); //Addamarkeratthecenterofthemap. addMarker(bangalore,map); } //Addsamarkertothemap. functionaddMarker(location,map){ //Addthemarkerattheclickedlocation,andaddthenext-availablelabel //fromthearrayofalphabeticalcharacters. newgoogle.maps.Marker({ position:location, label:labels[labelIndex++%labels.length], map:map, }); } window.initMap=initMap;index.js Note:TheJavaScriptiscompiledfromtheTypeScriptsnippet. Viewexample TrySample Stackblitz.com CodeSandbox.io JSFiddle.net GitPod.io GoogleCloudShell Complexicons Youcanspecifycomplexshapestoindicateregionsthatareclickable,and specifyhowtheiconsshouldappearrelativetootheroverlays(their "stackorder").Iconsspecifiedinthismannershouldsettheir icon propertiestoanobjectoftype Icon. Icon objectsdefineanimage.Theyalsodefinethesizeofthe icon,theoriginoftheicon(iftheimageyouwantispart ofalargerimageinasprite,forexample),andthe anchorwheretheicon'shotspotshouldbelocated(whichis basedontheorigin). Ifyouareusingalabelwithacustom marker,youcanpositionthelabelwiththe labelOriginpropertyinthe Icon object. Note:Markershadowswereremovedinversion3.14ofthe MapsJavaScriptAPI.Anyshadowsspecifiedprogrammatically willbeignored. TypeScript //Thefollowingexamplecreatescomplexmarkerstoindicatebeachesnear //Sydney,NSW,Australia.Notethattheanchorissetto(0,32)tocorrespond //tothebaseoftheflagpole. functioninitMap():void{ constmap=newgoogle.maps.Map( document.getElementById("map")asHTMLElement, { zoom:10, center:{lat:-33.9,lng:151.2}, } ); setMarkers(map); } //Dataforthemarkersconsistingofaname,aLatLngandazIndexforthe //orderinwhichthesemarkersshoulddisplayontopofeachother. constbeaches:[string,number,number,number][]=[ ["BondiBeach",-33.890542,151.274856,4], ["CoogeeBeach",-33.923036,151.259052,5], ["CronullaBeach",-34.028249,151.157507,3], ["ManlyBeach",-33.80010128657071,151.28747820854187,2], ["MaroubraBeach",-33.950198,151.259302,1], ]; functionsetMarkers(map:google.maps.Map){ //Addsmarkerstothemap. //MarkersizesareexpressedasaSizeofX,Ywheretheoriginoftheimage //(0,0)islocatedinthetopleftoftheimage. //Origins,anchorpositionsandcoordinatesofthemarkerincreaseintheX //directiontotherightandintheYdirectiondown. constimage={ url:"https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png", //Thismarkeris20pixelswideby32pixelshigh. size:newgoogle.maps.Size(20,32), //Theoriginforthisimageis(0,0). origin:newgoogle.maps.Point(0,0), //Theanchorforthisimageisthebaseoftheflagpoleat(0,32). anchor:newgoogle.maps.Point(0,32), }; //Shapesdefinetheclickableregionoftheicon.ThetypedefinesanHTML //element'poly'whichtracesoutapolygonasaseriesofX,Ypoints. //Thefinalcoordinateclosesthepolybyconnectingtothefirstcoordinate. constshape={ coords:[1,1,1,20,18,20,18,1], type:"poly", }; for(leti=0;ivoid; } } window.initMap=initMap;index.ts Note:ReadtheguideonusingTypeScriptandGoogleMaps. JavaScript //Thefollowingexamplecreatescomplexmarkerstoindicatebeachesnear //Sydney,NSW,Australia.Notethattheanchorissetto(0,32)tocorrespond //tothebaseoftheflagpole. functioninitMap(){ constmap=newgoogle.maps.Map(document.getElementById("map"),{ zoom:10, center:{lat:-33.9,lng:151.2}, }); setMarkers(map); } //Dataforthemarkersconsistingofaname,aLatLngandazIndexforthe //orderinwhichthesemarkersshoulddisplayontopofeachother. constbeaches=[ ["BondiBeach",-33.890542,151.274856,4], ["CoogeeBeach",-33.923036,151.259052,5], ["CronullaBeach",-34.028249,151.157507,3], ["ManlyBeach",-33.80010128657071,151.28747820854187,2], ["MaroubraBeach",-33.950198,151.259302,1], ]; functionsetMarkers(map){ //Addsmarkerstothemap. //MarkersizesareexpressedasaSizeofX,Ywheretheoriginoftheimage //(0,0)islocatedinthetopleftoftheimage. //Origins,anchorpositionsandcoordinatesofthemarkerincreaseintheX //directiontotherightandintheYdirectiondown. constimage={ url:"https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png", //Thismarkeris20pixelswideby32pixelshigh. size:newgoogle.maps.Size(20,32), //Theoriginforthisimageis(0,0). origin:newgoogle.maps.Point(0,0), //Theanchorforthisimageisthebaseoftheflagpoleat(0,32). anchor:newgoogle.maps.Point(0,32), }; //Shapesdefinetheclickableregionoftheicon.ThetypedefinesanHTML //element'poly'whichtracesoutapolygonasaseriesofX,Ypoints. //Thefinalcoordinateclosesthepolybyconnectingtothefirstcoordinate. constshape={ coords:[1,1,1,20,18,20,18,1], type:"poly", }; for(leti=0;i{ constmarker=newgoogle.maps.Marker({ position, map, title:`${i+1}.${title}`, label:`${i+1}`, optimized:false, }); //Addaclicklistenerforeachmarker,andsetuptheinfowindow. marker.addListener("click",()=>{ infoWindow.close(); infoWindow.setContent(marker.getTitle()); infoWindow.open(marker.getMap(),marker); }); }); } declareglobal{ interfaceWindow{ initMap:()=>void; } } window.initMap=initMap;index.ts Note:ReadtheguideonusingTypeScriptandGoogleMaps. JavaScript //Thefollowingexamplecreatesfiveaccessibleand //focusablemarkers. functioninitMap(){ constmap=newgoogle.maps.Map(document.getElementById("map"),{ zoom:12, center:{lat:34.84555,lng:-111.8035}, }); //SetLatLngandtitletextforthemarkers.Thefirstmarker(BoyntonPass) //receivestheinitialfocuswhentabispressed.Usearrowkeysto //movebetweenmarkers;presstabagaintocyclethroughthemapcontrols. consttourStops=[ [{lat:34.8791806,lng:-111.8265049},"BoyntonPass"], [{lat:34.8559195,lng:-111.7988186},"AirportMesa"], [{lat:34.832149,lng:-111.7695277},"ChapeloftheHolyCross"], [{lat:34.823736,lng:-111.8001857},"RedRockCrossing"], [{lat:34.800326,lng:-111.7665047},"BellRock"], ]; //Createaninfowindowtosharebetweenmarkers. constinfoWindow=newgoogle.maps.InfoWindow(); //Createthemarkers. tourStops.forEach(([position,title],i)=>{ constmarker=newgoogle.maps.Marker({ position, map, title:`${i+1}.${title}`, label:`${i+1}`, optimized:false, }); //Addaclicklistenerforeachmarker,andsetuptheinfowindow. marker.addListener("click",()=>{ infoWindow.close(); infoWindow.setContent(marker.getTitle()); infoWindow.open(marker.getMap(),marker); }); }); } window.initMap=initMap;index.js Note:TheJavaScriptiscompiledfromtheTypeScriptsnippet. Viewexample TrySample Stackblitz.com CodeSandbox.io JSFiddle.net GitPod.io GoogleCloudShell Animateamarker Youcananimatemarkerssothattheyexhibitdynamicmovementinavariety ofdifferentcircumstances.Tospecifythewayamarkerisanimated,use themarker'sanimationproperty,oftype google.maps.Animation.Thefollowing Animationvaluesaresupported: DROPindicatesthatthemarkershoulddropfromthetopof themaptoitsfinallocationwhenfirstplacedonthemap.Animation willceaseoncethemarkercomestorestandanimationwill reverttonull.Thistypeofanimationisusuallyspecified duringcreationoftheMarker. BOUNCEindicatesthatthemarkershouldbounceinplace.A bouncingmarkerwillcontinuebouncinguntilits animationpropertyisexplicitlysettonull. Youmayinitiateananimationonanexistingmarkerbycalling setAnimation()ontheMarkerobject. TypeScript //ThefollowingexamplecreatesamarkerinStockholm,SwedenusingaDROP //animation.ClickingonthemarkerwilltoggletheanimationbetweenaBOUNCE //animationandnoanimation. letmarker:google.maps.Marker; functioninitMap():void{ constmap=newgoogle.maps.Map( document.getElementById("map")asHTMLElement, { zoom:13, center:{lat:59.325,lng:18.07}, } ); marker=newgoogle.maps.Marker({ map, draggable:true, animation:google.maps.Animation.DROP, position:{lat:59.327,lng:18.067}, }); marker.addListener("click",toggleBounce); } functiontoggleBounce(){ if(marker.getAnimation()!==null){ marker.setAnimation(null); }else{ marker.setAnimation(google.maps.Animation.BOUNCE); } } declareglobal{ interfaceWindow{ initMap:()=>void; } } window.initMap=initMap;index.ts Note:ReadtheguideonusingTypeScriptandGoogleMaps. JavaScript //ThefollowingexamplecreatesamarkerinStockholm,SwedenusingaDROP //animation.ClickingonthemarkerwilltoggletheanimationbetweenaBOUNCE //animationandnoanimation. letmarker; functioninitMap(){ constmap=newgoogle.maps.Map(document.getElementById("map"),{ zoom:13, center:{lat:59.325,lng:18.07}, }); marker=newgoogle.maps.Marker({ map, draggable:true, animation:google.maps.Animation.DROP, position:{lat:59.327,lng:18.067}, }); marker.addListener("click",toggleBounce); } functiontoggleBounce(){ if(marker.getAnimation()!==null){ marker.setAnimation(null); }else{ marker.setAnimation(google.maps.Animation.BOUNCE); } } window.initMap=initMap;index.js Note:TheJavaScriptiscompiledfromtheTypeScriptsnippet. Viewexample TrySample Stackblitz.com CodeSandbox.io JSFiddle.net GitPod.io GoogleCloudShell Ifyouhavemanymarkers,youmightnotwanttodropthemonthemapall atonce.YoucanmakeuseofsetTimeout()tospaceyour markers'animationsusingapatternlikethatshownbelow: functiondrop(){ for(vari=0;i



請為這篇文章評分?