Mapbox Android SDK官方教程(五)——Events
Events
SDK提供多种方法来监听map事件,其中主要方法下面都会列出,你也会偶尔在其他相关API中发现其他监听器。
Map click & long click events
点击事件是在地图每一次被点击后会被回调,通常回调会提供当前点击位置的LatLng信息。增加下面的代码到你的应用中就可以设置监听点击事件。
Convert from screen pixel
偶尔你需要知道用户在屏幕上的交互位置,你可以将Latlng转为屏幕像素坐标。SDK提供了投影方法mapboxMap.getProjection().toScreenLocation(<LatLng>)来实现LatLng到屏幕坐标的转换,反过来也可以转换。
Latlng和pixel转换的常见用例是你获取图层或者数据源,例如判断用户否单击了POI。
Camera change events
地图的相机代表了看地图的视角,大多数情况下,你要通过和相机交互来调整地图的开始缩放等级和目标位置。用户也可以通过手势来操作相机视角,如旋转地图、调整俯仰角、单击调整位置。
SDK提供了实用的相机视角变化的监听,这些监听可以提醒你任何相机移动的信息。根据不同的来源如用户手势、内部API动画或者开发者控制移动,有不同的监听器,如下:
On fling & on scroll events
除了相机改变的监听器,SDK也提供了用户滚动和振动地图的监听器。滚动事件是在用户单手从上到下拖拽导致的相机位置的变化,滑动事件和滚动事件很类似,当用户做复杂手势时,同一时刻只会触发一种事件,使用如下:
Marker and info window events
SDK提供了用于监听用户点击markers的监听器。默认情况下,所有的markers都会有onMarkerClick事件来展示和隐藏信息窗口。你可以覆盖重写这个方法。
为了显示一个Toast信息提示,你可以重新maker点击监听方法,为了避免同时展示toast信息和信息窗口,在最后返回true:
类似的,信息窗口也提供了当信息窗口被单击、长击和关闭的监听器。使用如下:
Map change events
地图在被打开和变动时会经历一系列的事件,OnMapChangedListener方法可以提供你感兴趣事件的发生,这些事件包括地图何时开始和结束、何时载入地图样式、何时结束渲染。
不是通过MapBoxMap增加监听器,而是通过mapview的mapView.addOnMapChangedListener(OnMapChangeListener())。当地图变化事件触发时,回调onMapChanged方法。这个方法提供了一个整数值,这个值的意思可以对照下表来理解:
MapChange Constants | Description |
---|---|
REGION_WILL_CHANGE |
This event is triggered whenever the currently displayed map region is about to change without an animation. |
REGION_WILL_CHANGE_ANIMATED |
This event is triggered whenever the currently displayed map region is about to change with an animation. |
REGION_IS_CHANGING |
This event is triggered whenever the currently displayed map region is changing. |
REGION_DID_CHANGE |
This event is triggered whenever the currently displayed map region finished changing without an animation. |
REGION_DID_CHANGE_ANIMATED |
This event is triggered whenever the currently displayed map region finished changing with an animation. |
WILL_START_LOADING_MAP |
This event is triggered when the map is about to start loading a new map style. |
DID_FINISH_LOADING_MAP |
This is triggered when the map has successfully loaded a new map style. |
DID_FAIL_LOADING_MAP |
This event is triggered when the map has failed to load a new map style. |
WILL_START_RENDERING_FRAME |
This event is triggered when the map will start rendering a frame. |
DID_FINISH_RENDERING_FRAME |
This event is triggered when the map finished rendering a frame. |
DID_FINISH_RENDERING_FRAME_FULLY_RENDERED |
This event is triggered when the map finished rendering the frame fully. |
WILL_START_RENDERING_MAP |
This event is triggered when the map will start rendering the map. |
DID_FINISH_RENDERING_MAP |
This event is triggered when the map finished rendering the map. |
DID_FINISH_RENDERING_MAP_FULLY_RENDERED |
This event is triggered when the map is fully rendered. |
DID_FINISH_LOADING_STYLE |
Triggered when a style has finished loading. |
SOURCE_DID_CHANGE |
Triggered when a source attribution changes. |