object:addMarker()

类型 函数
对象 Map
native.*
返回值 数字
修订版 发行版 2024.3703
关键字 addMarker
请参阅 object:removeMarker()
object:removeAllMarkers()

概述

在指定位置向地图添加一个图钉。在轻触图钉时,将会在小弹出窗口中显示可选的标题和副标题。如果指定了自定义图片,则图片的底部中心将成为图钉位置。

此函数会返回已添加标记的识别号,或者在失败时返回 nil。此数字可与 object:removeMarker() 一起使用,以移除标记。

需要注意的事项

在设备上,可能需要延迟 object:addMarker(),直到设备的位置硬件激活后。一个解决方案是反复对位置硬件排队,直到收到适当的响应,然后调用此函数。有关详细信息,请参阅 object:getUserLocation() 中的示例。

语法

object:addMarker( latitude, longitude )
object:addMarker( latitude, longitude, options )
latitude (required)

数字. 标记的纬度(度数)。

longitude (required)

数字. 标记的经度(度数)。

options (optional)

. 用于标记的选项表,有关详细信息,请参阅下一部分。

选项参考

title (optional)

字符串. 当用户轻触标记时,将在弹出窗口中显示的标题。

subtitle (optional)

字符串. 当用户轻触标记时,将在弹出窗口中显示的副标题。

listener (optional)

函数. 在轻触标记时将被调用的侦听器。

imageFile (optional)

字符串. 用于标记的图片的文件名。默认基本目录是资源目录。它还可以是形式为{ baseDir=, filename= }。这将使用动态图像选择。坐标作为 mapMarker 返回。

示例

-- Map marker listener function
local function markerListener(event)
    print( "type: ", event.type )  -- event type
    print( "markerId: ", event.markerId )  -- ID of the marker that was touched
    print( "lat: ", event.latitude )  -- latitude of the marker
    print( "long: ", event.longitude )  -- longitude of the marker
end

-- Create a native map view
local myMap = native.newMapView( 0, 0, 300, 220 )
myMap.x = display.contentCenterX
myMap.y = display.contentCenterY

-- Sometime later (following activation of device location hardware)
local options = 
{ 
    title = "Displayed Title", 
    subtitle = "Subtitle text", 
    listener = markerListener,
    -- This will look in the resources directory for the image file
    imageFile =  "someImage.png",
    -- Alternatively, this looks in the specified directory for the image file
    -- imageFile = { filename="someImage.png", baseDir=system.TemporaryDirectory }
}
local result, errorMessage = myMap:addMarker( 37.331692, -122.030456, options )
if ( result ) then
    print( "Marker added" )
else
    print( errorMessage )
end