javascript 标记
by Tan Le Tian
谭乐天
如何使用JavaScript更改Google Maps标记的颜色 (How to change the color of Google Maps markers with JavaScript)
使它们成为粉红色,蓝色,绿色,黄色或紫色! (Make them pink, blue, green, yellow or purple!)
By default, the Google Maps marker is red in color. This article will show how to add different color markers to Google Maps. So, let’s get started. ?
默认情况下,Google地图标记为红色。 本文将介绍如何向Google地图添加不同的颜色标记。 因此,让我们开始吧。 ?
1.载入Google地图 (1. Load Google Maps)
Create an HTML file which loads Google Maps by following Google Maps API official docs: Hello World.
通过遵循Google Maps API官方文档,创建一个加载Google MapsHTML文件:Hello World 。
Your code will look something like the code snippet below.
您的代码看起来像下面的代码片段。
Note: Remember to change YOUR_API_KEY
to your actual Google Maps API key.
注意:请记住,将YOUR_API_KEY
更改为实际的Google Maps API密钥。
2.添加不同的颜色标记 (2. Add different color markers)
To add a blue color marker, we need to change the icon of the marker. This is done by adding an icon property and specifying a URL for it like below.
要添加蓝色标记,我们需要更改标记的图标。 这可以通过添加icon属性并为其指定URL来完成,如下所示。
icon: { url: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png" }
Note that we specify blue-dot.png
at the end of the URL to get a blue marker. To add a green marker simply change it to green-dot.png
so that the URL will be http://maps.google.com/mapfiles/ms/icons/green-dot.png
.
请注意,我们在网址末尾指定blue-dot.png
以获得蓝色标记。 要添加绿色标记,只需将其更改为green-dot.png
,以使URL为http://maps.google.com/mapfiles/ms/icons/green-dot.png
。
Some other colors available:
其他一些可用的颜色:
pink:
pink-dot.png
粉色:
pink-dot.png
yellow:
yellow-dot.png
黄色:
yellow-dot.png
purple:
purple-dot.png
紫色:
purple-dot.png
To get the URL of more marker icons, please refer to this website.
要获取更多标记图标的URL,请访问此网站 。
3.包装添加标记功能 (3. Wrap into add marker function)
To make the code cleaner, we can define an addMarker
function which takes in latLng
and color
of the marker. Note that we store the markers added in the a global markersArray
in case we need to perform any operations on the markers later.
为了使代码更addMarker
,我们可以定义一个addMarker
函数,该函数接受latLng
和标记的color
。 请注意,如果以后需要对标记执行任何操作,我们markersArray
添加的标记存储在全局markersArray
中。
Open the HTML file in the browser. It should look like this:
在浏览器中打开HTML文件。 它看起来应该像这样:
You can get the full final version of the code from here. Please let me know how it goes in the comments below.
您可以从此处获得代码的完整最终版本。 请在下面的评论中让我知道如何进行。
Feel free to check out another Google Maps tutorial I have written:Implement click on JavaScript Google Map to add draggable markers with polyline
随时查看我编写的另一本Google Maps教程: 实现对JavaScript Google Map的单击以使用多义线添加可拖动标记
翻译自: https://www.freecodecamp.org/news/how-to-change-javascript-google-map-marker-color-8a72131d1207/
javascript 标记