Markers | Maps JavaScript API - Google Developers
文章推薦指數: 80 %
// 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;i
延伸文章資訊
- 1Google Maps JS API v3 - Simple Multiple Marker Example
Fairly new to the Google Maps Api. I've got an array of data that I want to cycle through and plo...
- 2Google Maps - Markers - Tutorialspoint
Adding a Simple Marker. You can add a simple marker to the map at a desired location by instantia...
- 3遊記ep.28 Marker labels in Google村 - iT 邦幫忙
var image = 'https://developers.google.com/maps/documentation/javascript/ ... In the following ex...
- 4Simple Markers | Maps JavaScript API - Google Developers
This example identifies a location on the map with a marker. ... git clone -b sample-marker-simpl...
- 5Google Maps Marker - Happy Coding
This project uses the Google Maps API to create a map that shows a marker. View the code for this...