Commit c5a91ed7 authored by wind.wang's avatar wind.wang

init

parents
# Changelog
init project to ability platform
#1.2.8
修复安卓和ios多个map之间的跳转时,前一个页面的mark点击失效问题
#1.2.8
添加了 onMoveComplete函数,onMoveComplete 与 onChange只能二选一, onMoveComplete在移动地图的时候中心点变了都会调用
# 1.3.0
添加了 onMovingChange 回调函数
#2.0.0
集成github比较好的mapview组件,修复了一些bug
https://github.com/qiuxiang/react-native-amap3d
#2.0.1
重命名一些文件的名称,修复了ios的一些bug
#2.0.2-amap2d
s.dependency 'React'
#2.0.2-amap2d.3
web端的定位 AMap变量改为 window.AMap
#2.0.2-amap2d.4
中心点偶然会偏移
#2.0.2-amap2d.5
fetchLocation 错误信息安卓支持 if(error) 判断
\ No newline at end of file
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
.externalNativeBuild
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>android</name>
<comment>Project android created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>
arguments=
auto.sync=false
build.scans.enabled=false
connection.gradle.distribution=GRADLE_DISTRIBUTION(LOCAL_INSTALLATION(/Applications/Android Studio.app/Contents/gradle/gradle-3.2))
connection.project.dir=
eclipse.preferences.version=1
gradle.user.home=/Applications/Android Studio.app/Contents/gradle/gradle-3.2
java.home=
jvm.arguments=
offline.mode=false
override.workspace.settings=true
show.console.view=true
show.executions.view=true
apply plugin: 'com.android.library'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
}
}
}
buildscript {
ext.kotlin_version = '1.2.41'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
}
}
allprojects {
repositories {
jcenter()
maven { url "$projectDir/../node_modules/react-native/android" }
}
}
dependencies {
compile 'com.android.support:appcompat-v7:23.1.0'
compile files('libs/AMap_Search_V4.0.0_20170111.jar')
compile files('libs/AMap_Location_V3.3.0_20170118.jar')
compile 'com.facebook.react:react-native:+'
}
\ No newline at end of file
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
#Mon Dec 28 10:00:20 PST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.terminus.rctamap">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
</manifest>
package io.terminus.rnamap;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import io.terminus.rnamap.service.GeocodeManager;
import io.terminus.rnamap.service.LocationManager;
import io.terminus.rnamap.service.MapNavigationManager;
/**
* io.terminus.rnamap
* Created by Allen.Chiang on 19/01/2017.
*/
public class AMapReactPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new LocationManager(reactContext));
modules.add(new GeocodeManager(reactContext));
modules.add(new MapNavigationManager(reactContext));
return modules;
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
List<ViewManager> modules = new ArrayList<>();
return modules;
}
}
package io.terminus.rnamap;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.StreetNumber;
import io.terminus.rnamap.model.LocationDO;
/**
* io.terminus.rnamap
* Created by Allen.Chiang on 22/01/2017.
*/
public class AMapUtils {
public static LocationDO createLocationDO(AMapLocation aMapLocation) {
LocationDO locationDO = new LocationDO();
locationDO.setLatitude(String.valueOf(aMapLocation.getLatitude()));
locationDO.setLongitude(String.valueOf(aMapLocation.getLongitude()));
locationDO.setAdCode(aMapLocation.getAdCode());
locationDO.setFormattedAddress(aMapLocation.getAddress());
locationDO.setCountry(aMapLocation.getCountry());
locationDO.setProvince(aMapLocation.getProvince());
locationDO.setCity(aMapLocation.getCity());
locationDO.setDistrict(aMapLocation.getDistrict());
locationDO.setCityCode(aMapLocation.getCityCode());
locationDO.setStreet(aMapLocation.getStreet());
locationDO.setNumber(aMapLocation.getStreetNum());
locationDO.setPOIName(aMapLocation.getPoiName());
locationDO.setAOIName(aMapLocation.getAoiName());
return locationDO;
}
/**
* 和iOS统一返回格式
*
* @param address address
* @return LocationDO
*/
public static LocationDO convert2Location(RegeocodeAddress address) {
LocationDO locationDO = new LocationDO();
locationDO.setFormattedAddress(address.getFormatAddress());
locationDO.setCountry(address.getTownship());
locationDO.setProvince(address.getProvince());
locationDO.setCityCode(address.getCityCode());
locationDO.setCity(address.getCity());
locationDO.setDistrict(address.getDistrict());
locationDO.setAdCode(address.getAdCode());
StreetNumber streetNumber = address.getStreetNumber();
if (streetNumber != null) {
LatLonPoint point = streetNumber.getLatLonPoint();
if (point != null) {
locationDO.setLatitude(String.valueOf(point.getLatitude()));
locationDO.setLongitude(String.valueOf(point.getLongitude()));
}
locationDO.setStreet(streetNumber.getStreet());
locationDO.setNumber(streetNumber.getNumber());
}
return locationDO;
}
/**
* 和iOS统一返回格式
*
* @param address address
* @return LocationDO
*/
public static LocationDO convert2Location(GeocodeAddress address) {
LocationDO locationDO = new LocationDO();
locationDO.setFormattedAddress(address.getFormatAddress());
locationDO.setCountry(address.getTownship());
locationDO.setProvince(address.getProvince());
locationDO.setCity(address.getCity());
// android这里没有返回citycode,但是ios有返回,这里可能导致不一样
locationDO.setAdCode(address.getAdcode());
LatLonPoint point = address.getLatLonPoint();
if (point != null) {
locationDO.setLatitude(String.valueOf(point.getLatitude()));
locationDO.setLongitude(String.valueOf(point.getLongitude()));
}
return locationDO;
}
public static Boolean isStringBlank(String str) {
if (str == null || str.length() == 0 || str.trim().length() == 0) {
return true;
}
return false;
}
public static void navigation(Context mContext,
String sname,
double slat,
double slon,
String dname,
double dlat,
double dlon){
if(!isMapInstall(mContext)){
Toast.makeText(mContext,"请下载安装高德地图",Toast.LENGTH_SHORT).show();
return;
}
String dat = "androidamap://route?sourceApplication="+mContext.getPackageName()+"&slat="+slat+"&slon="+slon+"&sname="+sname+"&dlat="+dlat+"&dlon="+dlon+"&dname="+dname+"&dev=0&t=2";
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse(dat));
mContext.startActivity(intent);
}
public static boolean isMapInstall(Context mContext){
try {
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo("com.autonavi.minimap", PackageManager.GET_UNINSTALLED_PACKAGES);
if(info != null){
return true;
}
}catch (Exception e){
e.printStackTrace();
}
return false;
}
}
package io.terminus.rnamap.model;
/**
* Created by wenboli on 17/7/12.
*/
import com.amap.api.services.district.DistrictItem;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import java.util.ArrayList;
import java.util.List;
public class DistrictResultDO implements WritableObject {
private String latitude;
private String longitude;
private String adcode;
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLatitude() {
return latitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLongitude() {
return longitude;
}
public void setAdcode(String adcode) {
this.adcode = adcode;
}
public String getAdcode() {
return adcode;
}
public DistrictResultDO(DistrictItem districtItem) {
latitude = String.valueOf(districtItem.getCenter().getLatitude());
longitude = String.valueOf(districtItem.getCenter().getLongitude()) ;
adcode = districtItem.getAdcode();
}
public WritableMap writableMap() {
WritableMap writableMap = Arguments.createMap();
writableMap.putString("adCode", adcode);
writableMap.putString("latitude", latitude);
writableMap.putString("longitude", longitude);
return writableMap;
}
}
package io.terminus.rnamap.model;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import java.util.Map;
/**
* io.terminus.rnamap.model
* Created by Allen.Chiang on 19/01/2017.
*/
public class ErrorDO implements WritableObject {
private String message;
private Integer code;
private Map<String, String> userInfo;
public ErrorDO(String message, Integer code) {
this.message = message;
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public Map<String, String> getUserInfo() {
return userInfo;
}
public void setUserInfo(Map<String, String> userInfo) {
this.userInfo = userInfo;
}
@Override
public WritableMap writableMap() {
WritableMap map = Arguments.createMap();
map.putString("message", message);
map.putInt("code", code);
if (null != userInfo) {
WritableMap userInfoMap = Arguments.createMap();
for (Map.Entry<String, String> entry : userInfo.entrySet()) {
userInfoMap.putString(entry.getKey(), entry.getValue());
}
map.putMap("userInfo", userInfoMap);
}
return map;
}
}
package io.terminus.rnamap.model;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import java.util.List;
/**
* io.terminus.rnamap.model
* Created by Allen.Chiang on 19/01/2017.
*/
public class LocationDO implements WritableObject {
// gps坐标信息,纬度
private String latitude;
// gps坐标信息,经度
private String longitude;
// 格式化地址
private String formattedAddress;
// 国家
private String country;
// 省
private String province;
// 市
private String city;
// 区
private String district;
// 城市编码
private String cityCode;
// 区域编码
private String adCode;
// 街道名称
private String street;
// 门牌号
private String number;
// 兴趣点名称
private String POIName;
// 所属兴趣点名称
private String AOIName;
// 周边兴趣点
private List<POIDO> poidoList;
// 周边兴趣点所属
private List<String> aoidoList;
public WritableMap writableMap() {
WritableMap map = Arguments.createMap();
map.putString("latitude", latitude);
map.putString("longitude", longitude);
map.putString("formattedAddress", formattedAddress);
map.putString("country", country);
map.putString("province", province);
map.putString("city", city);
map.putString("district", district);
map.putString("cityCode", cityCode);
map.putString("adCode", adCode);
map.putString("street", street);
map.putString("number", number);
map.putString("POIName", POIName);
map.putString("AOIName", AOIName);
WritableArray pois = Arguments.createArray();
if (poidoList != null) {
for (POIDO poido : poidoList) {
pois.pushMap(poido.writableMap());
}
}
WritableArray aois = Arguments.createArray();
if (aoidoList != null) {
for (String aoido : aoidoList) {
aois.pushString(aoido);
}
}
map.putArray("aois", aois);
map.putArray("pois", pois);
return map;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getFormattedAddress() {
return formattedAddress;
}
public void setFormattedAddress(String formattedAddress) {
this.formattedAddress = formattedAddress;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getAdCode() {
return adCode;
}
public void setAdCode(String adCode) {
this.adCode = adCode;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getPOIName() {
return POIName;
}
public void setPOIName(String POIName) {
this.POIName = POIName;
}
public String getAOIName() {
return AOIName;
}
public void setAOIName(String AOIName) {
this.AOIName = AOIName;
}
public List<POIDO> getPoidoList() {
return poidoList;
}
public void setPoidoList(List<POIDO> poidoList) {
this.poidoList = poidoList;
}
public List<String> getAoidoList() {
return aoidoList;
}
public void setAoidoList(List<String> aoidoList) {
this.aoidoList = aoidoList;
}
}
package io.terminus.rnamap.model;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import java.util.ArrayList;
import java.util.List;
/**
* io.terminus.rnamap.model
* Created by Allen.Chiang on 20/01/2017.
*/
public class LocationListDO implements WritableObject {
private List<LocationDO> list;
public LocationListDO(List<LocationDO> list) {
this.list = list;
}
public void addLocation(LocationDO locationDO) {
if (this.list == null) {
this.list = new ArrayList<>();
}
this.list.add(locationDO);
}
@Override
public WritableMap writableMap() {
WritableArray writableArray = Arguments.createArray();
if (list != null) {
for (LocationDO locationDO : list) {
writableArray.pushMap(locationDO.writableMap());
}
}
WritableMap writableMap = Arguments.createMap();
writableMap.putArray("list", writableArray);
return writableMap;
}
}
package io.terminus.rnamap.model;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableType;
import java.util.Map;
/**
* User : yh
* Date : 17/3/8
*/
public class MapPointDO {
public MapPointDO(ReadableMap data){
if(data.hasKey("latitude")){
latitude = data.getDouble("latitude");
}
if(data.hasKey("longitude")){
longitude = data.getDouble("longitude");
}
if(data.hasKey("title")){
title = data.getString("title");
}
if(data.hasKey("subTitle")){
subTitle = data.getString("subTitle");
}
if(data.hasKey("desc")){
desc = data.getString("desc");
}
if(data.hasKey("iconImageName")){
iconImageName = data.getString("iconImageName");
}
if(data.hasKey("extra")){
extra = data.getString("extra");
}
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getIconImageName() {
return iconImageName;
}
public void setIconImageName(String iconImageName) {
this.iconImageName = iconImageName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
private double latitude;
private double longitude;
private String iconImageName;
private String title;
private String subTitle;
private String desc;
private String extra;
}
package io.terminus.rnamap.model;
import com.amap.api.services.core.PoiItem;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
/**
* io.terminus.rnamap.model
* Created by Allen.Chiang on 23/01/2017.
*/
public class POIDO implements WritableObject {
private String uid;
private String name;
private String type;
private String address;
private String adcode;
private String latitude;
private String longitude;
public void setPoiItem(PoiItem poiItem) {
this.uid = poiItem.getPoiId();
this.name = poiItem.getTitle();
this.type = poiItem.getTypeDes();
this.adcode = poiItem.getAdCode();
this.address = poiItem.getSnippet();
if (poiItem.getLatLonPoint() != null) {
latitude = String.valueOf(poiItem.getLatLonPoint().getLatitude());
longitude = String.valueOf(poiItem.getLatLonPoint().getLongitude());
}
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getAdcode() {
return adcode;
}
public void setAdcode(String adcode) {
this.adcode = adcode;
}
@Override
public WritableMap writableMap() {
WritableMap writableMap = Arguments.createMap();
writableMap.putString("uid", uid);
writableMap.putString("name", name);
writableMap.putString("type", type);
writableMap.putString("address", address);
writableMap.putString("adcode", adcode);
writableMap.putString("latitude", latitude);
writableMap.putString("longitude", longitude);
return writableMap;
}
}
package io.terminus.rnamap.model;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import java.util.ArrayList;
import java.util.List;
/**
* io.terminus.rnamap.model
* Created by Allen.Chiang on 20/01/2017.
*/
public class POISearchDO implements WritableObject {
private List<POIDO> pois;
private Integer count;
private POISuggestion suggestion;
public POISearchDO() {
pois = new ArrayList<>();
count = 0;
suggestion = new POISuggestion();
}
@Override
public WritableMap writableMap() {
WritableMap writableMap = Arguments.createMap();
if (pois != null) {
WritableArray array = Arguments.createArray();
for (POIDO poido : pois) {
array.pushMap(poido.writableMap());
}
writableMap.putArray("pois", array);
}
writableMap.putInt("count", count);
writableMap.putMap("suggestion", suggestion == null ? null : suggestion.writableMap());
return writableMap;
}
public List<POIDO> getPois() {
return pois;
}
public void setPois(List<POIDO> pois) {
this.pois = pois;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public POISuggestion getSuggestion() {
return suggestion;
}
public void setSuggestion(POISuggestion suggestion) {
this.suggestion = suggestion;
}
public static class POISuggestion implements WritableObject {
private List<String> keywords;
public List<String> getKeywords() {
return keywords;
}
public void setKeywords(List<String> keywords) {
this.keywords = keywords;
}
@Override
public WritableMap writableMap() {
WritableMap writableMap = Arguments.createMap();
if (keywords != null) {
WritableArray array = Arguments.createArray();
for (String keyword : keywords) {
array.pushString(keyword);
}
writableMap.putArray("keywords", array);
}
return writableMap;
}
}
}
package io.terminus.rnamap.model;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
/**
* io.terminus.rnamap.model
* Created by Allen.Chiang on 19/01/2017.
*/
public class ReactResultDO implements WritableObject {
private String requestId;
private WritableObject data;
private WritableObject error;
public ReactResultDO() {
}
public ReactResultDO(String requestId) {
this.requestId = requestId;
}
public ReactResultDO(String requestId, WritableObject data) {
this.requestId = requestId;
this.data = data;
}
public WritableMap writableMap() {
WritableMap map = Arguments.createMap();
map.putString("requestId", requestId);
map.putMap("data", data == null ? null : data.writableMap());
map.putMap("error", error == null ? null : error.writableMap());
return map;
}
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public WritableObject getData() {
return data;
}
public void setData(WritableObject data) {
this.data = data;
}
public WritableObject getError() {
return error;
}
public void setError(WritableObject error) {
this.error = error;
}
}
package io.terminus.rnamap.model;
import com.facebook.react.bridge.WritableMap;
/**
* io.terminus.rnamap.model
* Created by Allen.Chiang on 19/01/2017.
*/
public interface WritableObject {
WritableMap writableMap();
}
package io.terminus.rnamap.searcher;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import io.terminus.rnamap.model.ErrorDO;
import io.terminus.rnamap.model.ReactResultDO;
import io.terminus.rnamap.model.WritableObject;
/**
* io.terminus.rnamap.service
* Created by Allen.Chiang on 20/01/2017.
*/
public class BaseEmitter {
private String requestId;
private ReactContext reactContext;
public BaseEmitter(String requestId, ReactContext reactContext) {
this.requestId = requestId;
this.reactContext = reactContext;
}
public ReactContext getReactContext() {
return reactContext;
}
public void sendEvent(String eventName, WritableMap writableMap) {
if (this.reactContext != null) {
writableMap.putString("requestId", requestId);
this.reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, writableMap);
}
}
public void sendEvent(String eventName, WritableObject writableObject) {
ReactResultDO resultDO = new ReactResultDO(requestId, writableObject);
this.sendEvent(eventName, resultDO.writableMap());
}
public void sendEventError(String eventName, ErrorDO errorDO) {
ReactResultDO resultDO = new ReactResultDO(requestId, errorDO);
sendEvent(eventName, resultDO.writableMap());
}
}
package io.terminus.rnamap.searcher;
/**
* Created by wenboli on 17/7/12.
*/
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.district.DistrictItem;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import java.util.ArrayList;
import java.util.List;
import io.terminus.rnamap.AMapUtils;
import io.terminus.rnamap.model.DistrictResultDO;
import io.terminus.rnamap.model.ErrorDO;
import io.terminus.rnamap.model.LocationDO;
import io.terminus.rnamap.model.LocationListDO;
import io.terminus.rnamap.model.POIDO;
public class DistrictSearcher extends BaseEmitter implements DistrictSearch.OnDistrictSearchListener{
private static final int RESULT_CODE_SUCCESS = 1000;
private static final String EVENT_NAME_GEOCODE = "geocode";
private DistrictSearch search;
public DistrictSearcher(String requestId, ReactContext reactContext) {
super(requestId, reactContext);
search = new DistrictSearch(reactContext);
}
public void search(String key){
DistrictSearchQuery query = new DistrictSearchQuery();
query.setKeywords(key);
search.setQuery(query);
search.setOnDistrictSearchListener(this);
search.searchDistrictAsyn();
}
@Override
public void onDistrictSearched(DistrictResult districtResult) {
if (districtResult.getAMapException().getErrorCode() == RESULT_CODE_SUCCESS){
DistrictItem item = districtResult.getDistrict().get(0);
DistrictResultDO resultDO = new DistrictResultDO(item);
sendEvent(EVENT_NAME_GEOCODE, resultDO);
} else {
ErrorDO errorDO = new ErrorDO("AMap DistrictSearch error with code:", 0);
sendEventError(EVENT_NAME_GEOCODE, errorDO);
}
}
}
package io.terminus.rnamap.searcher;
import android.text.TextUtils;
import android.util.Log;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.AoiItem;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.geocoder.StreetNumber;
import com.facebook.react.bridge.ReactContext;
import java.util.ArrayList;
import java.util.List;
import io.terminus.rnamap.AMapUtils;
import io.terminus.rnamap.model.ErrorDO;
import io.terminus.rnamap.model.LocationDO;
import io.terminus.rnamap.model.LocationListDO;
import io.terminus.rnamap.model.POIDO;
/**
* io.terminus.rnamap
* Created by Allen.Chiang on 20/01/2017.
*/
public class GeocodeSearcher extends BaseEmitter implements GeocodeSearch.OnGeocodeSearchListener {
private static final int RESULT_CODE_SUCCESS = 1000;
private static final String EVENT_NAME_GEOCODE = "geocode";
public GeocodeSearch geocodeSearch = null;
public GeocodeSearcher(ReactContext context, String requestId) {
super(requestId, context);
this.geocodeSearch = new GeocodeSearch(context);
geocodeSearch.setOnGeocodeSearchListener(this);
}
@Override
public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int resultCode) {
if (RESULT_CODE_SUCCESS == resultCode) {
LocationDO locationDO = AMapUtils.convert2Location(regeocodeResult.getRegeocodeAddress());
List<PoiItem> poiItems = regeocodeResult.getRegeocodeAddress().getPois();
List<AoiItem> aoiItems = regeocodeResult.getRegeocodeAddress().getAois();
String adCode = regeocodeResult.getRegeocodeAddress().getAdCode();
if (poiItems != null) {
List<POIDO> pois = new ArrayList<>();
for (PoiItem poiItem : poiItems) {
POIDO poido = new POIDO();
poido.setPoiItem(poiItem);
if(!TextUtils.isEmpty(adCode)){
if(TextUtils.isEmpty(poido.getAdcode())){
poido.setAdcode(adCode);
}
}
pois.add(poido);
}
locationDO.setPoidoList(pois);
// locationDO.setAoidoList();
}
if (aoiItems != null) {
List<String> aois = new ArrayList<>();
for (AoiItem aoiItem : aoiItems) {
aois.add(aoiItem.getAoiName());
}
locationDO.setAoidoList(aois);
}
this.sendEvent(EVENT_NAME_GEOCODE, locationDO);
} else {
ErrorDO errorDO = new ErrorDO("AMap ReGeocode error with code:" + resultCode, resultCode);
this.sendEventError(EVENT_NAME_GEOCODE, errorDO);
}
}
@Override
public void onGeocodeSearched(GeocodeResult geocodeResult, int resultCode) {
if (RESULT_CODE_SUCCESS == resultCode && !geocodeResult.getGeocodeAddressList().isEmpty()) {
List<LocationDO> locations = new ArrayList<>();
for (GeocodeAddress address : geocodeResult.getGeocodeAddressList()) {
LocationDO locationDO = AMapUtils.convert2Location(address);
locations.add(locationDO);
}
LocationListDO listDO = new LocationListDO(locations);
this.sendEvent(EVENT_NAME_GEOCODE, listDO);
} else {
ErrorDO errorDO = null;
if (geocodeResult.getGeocodeAddressList().isEmpty()) {
errorDO = new ErrorDO("AMap ReGeocode success but result is empty", resultCode);
} else {
errorDO = new ErrorDO("AMap ReGeocode error with code:" + resultCode, resultCode);
}
this.sendEventError(EVENT_NAME_GEOCODE, errorDO);
}
}
}
package io.terminus.rnamap.searcher;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.facebook.react.bridge.ReactContext;
import java.util.ArrayList;
import java.util.List;
import io.terminus.rnamap.AMapUtils;
import io.terminus.rnamap.model.ErrorDO;
import io.terminus.rnamap.model.LocationDO;
import io.terminus.rnamap.model.POIDO;
import io.terminus.rnamap.model.POISearchDO;
/**
* io.terminus.rnamap.service
* Created by Allen.Chiang on 20/01/2017.
*/
public class POISearcher extends BaseEmitter implements PoiSearch.OnPoiSearchListener, AMapLocationListener {
private static final int RESULT_CODE_SUCCESS = 1000;
private static final int POI_SEARCH_PAGE_SIZE = 10;
private static final String EVENT_NAME_GEOCODE = "geocode";
public PoiSearch poiSearch = null;
private Integer pageNum = 0;
private Integer pageSize = POI_SEARCH_PAGE_SIZE;
private String keyword;
public POISearcher(ReactContext reactContext, String requestId) {
super(requestId, reactContext);
}
public void search(String keyword, String cityCode) {
search(keyword, cityCode, pageNum, pageSize);
}
public void search(String keyword, String cityCode, Integer pageNum, Integer pageSize) {
PoiSearch.Query query = new PoiSearch.Query(keyword, "", cityCode);
query.setPageNum(pageNum);
query.setPageSize(pageSize);
query.setCityLimit(true);
poiSearch = new PoiSearch(this.getReactContext(), query);
poiSearch.setOnPoiSearchListener(this);
poiSearch.searchPOIAsyn();
}
@Override
public void onPoiSearched(PoiResult poiResult, int resultCode) {
if (RESULT_CODE_SUCCESS == resultCode) {
POISearchDO searchDO = new POISearchDO();
// 没有返回总数,只能这么粗略计算了
searchDO.setCount(poiResult.getPageCount() * poiResult.getPois().size());
// 建议搜索内容
searchDO.getSuggestion().setKeywords(poiResult.getSearchSuggestionKeywords());
if (poiResult.getPois() != null) {
List<POIDO> pois = new ArrayList<>();
for (PoiItem poiItem : poiResult.getPois()) {
POIDO poido = new POIDO();
poido.setPoiItem(poiItem);
pois.add(poido);
}
searchDO.setPois(pois);
}
sendEvent(EVENT_NAME_GEOCODE, searchDO);
} else {
ErrorDO errorDO = new ErrorDO("AMap POISearch error with code:" + resultCode, resultCode);
sendEventError(EVENT_NAME_GEOCODE, errorDO);
}
}
@Override
public void onPoiItemSearched(PoiItem poiItem, int resultCode) {
}
/**
* 定位的回调方法
*
* @param aMapLocation aMapLocation
*/
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
LocationDO locationDO = AMapUtils.createLocationDO(aMapLocation);
if (keyword != null) {
// js没有传入cityCode,自动获取一次定位以后并搜索poi
search(keyword, locationDO.getCityCode(), pageNum, pageSize);
}
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
}
package io.terminus.rnamap.service;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import io.terminus.rnamap.AMapUtils;
import io.terminus.rnamap.searcher.GeocodeSearcher;
import io.terminus.rnamap.searcher.POISearcher;
import io.terminus.rnamap.searcher.DistrictSearcher;
/**
* io.terminus.rnamap.service
* Created by Allen.Chiang on 19/01/2017.
*/
public class GeocodeManager extends ReactContextBaseJavaModule {
public GeocodeManager(ReactApplicationContext reactContext) {
super(reactContext);
}
@ReactMethod
public void geocode(String requestId, String address, String cityCode) {
GeocodeSearcher searcher = new GeocodeSearcher(this.getReactApplicationContext(), requestId);
GeocodeQuery query = new GeocodeQuery(address, cityCode);
searcher.geocodeSearch.getFromLocationNameAsyn(query);
}
@ReactMethod
public void reGeocode(String requestId, String latitude, String longitude) {
GeocodeSearcher searcher = new GeocodeSearcher(this.getReactApplicationContext(), requestId);
LatLonPoint point = new LatLonPoint(Double.parseDouble(latitude), Double.parseDouble(longitude));
RegeocodeQuery query = new RegeocodeQuery(point, 200, GeocodeSearch.GPS);
searcher.geocodeSearch.getFromLocationAsyn(query);
}
@ReactMethod
public void reGeocodeByAmap(String requestId, String latitude, String longitude){
GeocodeSearcher searcher = new GeocodeSearcher(this.getReactApplicationContext(), requestId);
LatLonPoint point = new LatLonPoint(Double.parseDouble(latitude), Double.parseDouble(longitude));
RegeocodeQuery query = new RegeocodeQuery(point, 200, GeocodeSearch.AMAP);
searcher.geocodeSearch.getFromLocationAsyn(query);
}
@ReactMethod
public void poiSearch(String requestId, String keyword, String cityCode) {
poiSearchWithPage(requestId, keyword, cityCode, 0, 10);
}
@ReactMethod
public void poiSearchWithPage(String requestId, String keyword, String cityCode, Integer pageNum, Integer pageSize) {
POISearcher searcher = new POISearcher(this.getReactApplicationContext(), requestId);
if (AMapUtils.isStringBlank(cityCode)) {
LocationManager locationManager = new LocationManager(this.getReactApplicationContext());
locationManager.location(searcher);
searcher.setKeyword(keyword);
searcher.setPageNum(pageNum);
searcher.setPageSize(pageSize);
} else {
searcher.search(keyword, cityCode, pageNum, pageSize);
}
}
@ReactMethod
public void district(String requestId, String name) {
DistrictSearcher searcher = new DistrictSearcher(requestId, this.getReactApplicationContext());
searcher.search(name);
}
@Override
public String getName() {
return "RNGeocodeManager";
}
}
package io.terminus.rnamap.service;
import android.support.v7.appcompat.BuildConfig;
import android.util.Log;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import javax.annotation.Nullable;
import io.terminus.rnamap.AMapUtils;
import io.terminus.rnamap.model.ErrorDO;
import io.terminus.rnamap.model.LocationDO;
import io.terminus.rnamap.model.ReactResultDO;
/**
* io.terminus.rnamap
* Created by Allen.Chiang on 19/01/2017.
*/
public class LocationManager extends ReactContextBaseJavaModule implements AMapLocationListener {
private static final String REACT_EVENT_NAME = "AMapLocationResultEvent";
public LocationManager(ReactApplicationContext reactContext) {
super(reactContext);
}
private AMapLocationClient aMapLocationClient = null;
@Override
public String getName() {
return "RNLocationManager";
}
/**
* 开始定位
*
* @param locationListener 可以外部传入定位结果的接收者,
* 用于poisearch自动获取一次定位的citycode
*/
public void location(AMapLocationListener locationListener) {
// if(ContextCompat.checkSelfPermission(getReactApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION)
// != PackageManager.PERMISSION_GRANTED){
// ReactResultDO resultDO = new ReactResultDO();
// resultDO.setError(new ErrorDO("", 2));
// sendEvent(this.getReactApplicationContext(), REACT_EVENT_NAME, resultDO.writableMap());
// return;
// }
AMapLocationClient locationClient = initAMapLocationClient();
aMapLocationClient = locationClient;
//设置定位回调监听
locationClient.setLocationListener(locationListener == null ? this : locationListener);
locationClient.startLocation();
}
/**
* 开始定位
*/
@ReactMethod
public void location() {
location(null);
}
@ReactMethod
public void stopLocation() {
if (aMapLocationClient != null) {
aMapLocationClient.stopLocation();
}
}
private AMapLocationClient initAMapLocationClient() {
//声明AMapLocationClient类对象
AMapLocationClient mLocationClient = new AMapLocationClient(getReactApplicationContext());
//声明AMapLocationClientOption对象
AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
mLocationOption.setOnceLocation(true); // 仅单次定位
mLocationOption.setOnceLocationLatest(true); // 获取最近3s内精度最高的一次定位结果
mLocationOption.setNeedAddress(true); // 设置是否返回地址信息(默认返回地址信息)
mLocationOption.setMockEnable(BuildConfig.DEBUG); // Debug模式允许mock gps
mLocationClient.setLocationOption(mLocationOption);
return mLocationClient;
}
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (aMapLocation == null) {
Log.e("AMapLocation error", "return null");
ReactResultDO resultDO = new ReactResultDO();
resultDO.setError(new ErrorDO("AMap return nothing", 0));
sendEvent(this.getReactApplicationContext(), REACT_EVENT_NAME, resultDO.writableMap());
} else if (aMapLocation.getErrorCode() != 0) {
Log.e("AMapLocation error", "Code:" + aMapLocation.getErrorCode() + ", Message:" + aMapLocation.getErrorInfo());
ReactResultDO resultDO = new ReactResultDO();
// 去掉sdk返回的一堆错误说明,只去空格前面一段字符串
String errorInfo = (aMapLocation.getErrorInfo()==null)?"":aMapLocation.getErrorInfo().split(" ")[0];
resultDO.setError(new ErrorDO(errorInfo, aMapLocation.getErrorCode()));
sendEvent(this.getReactApplicationContext(), REACT_EVENT_NAME, resultDO.writableMap());
} else {
LocationDO locationDO = AMapUtils.createLocationDO(aMapLocation);
ReactResultDO resultDO = new ReactResultDO(null, locationDO);
sendEvent(resultDO);
}
}
private void sendEvent(@Nullable ReactResultDO resultDO) {
sendEvent(this.getReactApplicationContext(), REACT_EVENT_NAME,
resultDO == null ? null : resultDO.writableMap());
}
private void sendEvent(ReactContext reactContext,
String eventName,
@Nullable WritableMap params) {
if (reactContext != null) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
}
}
package io.terminus.rnamap.service;
import android.widget.Toast;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import io.terminus.rnamap.AMapUtils;
/**
* User : yh
* Date : 17/8/3
*/
public class MapNavigationManager extends ReactContextBaseJavaModule {
private static final String REACT_MODULE_NAME = "RNMapNavigationManager";
private static final String SNAME = "sname";
private static final String SLAT = "slat";
private static final String SLON = "slon";
private static final String DNAME = "dname";
private static final String DLAT = "dlat";
private static final String DLON = "dlon";
public MapNavigationManager(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return REACT_MODULE_NAME;
}
@ReactMethod
public void mapNavigation(ReadableMap params){
String sname,dname;
double slat,slon,dlat,dlon;
if(!params.hasKey(SNAME)){
return;
}
if(!params.hasKey(DNAME)){
return;
}
if(!params.hasKey(SLAT)){
return;
}
if(!params.hasKey(SLON)){
return;
}
if(!params.hasKey(DLAT)){
return;
}
if(!params.hasKey(DLON)){
return;
}
sname = params.getString(SNAME);
dname = params.getString(DNAME);
slat = params.getDouble(SLAT);
slon = params.getDouble(SLON);
dlat = params.getDouble(DLAT);
dlon = params.getDouble(DLON);
AMapUtils.navigation(this.getReactApplicationContext(),
sname,
slat,
slon,
dname,
dlat,
dlon);
}
}
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
buildscript {
ext.kotlin_version = '1.2.41'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
minSdkVersion 16
targetSdkVersion 22
}
}
dependencies {
provided 'com.facebook.react:react-native:+'
compile 'com.amap.api:map2d:5.2.0'
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.qiuxiang.react.amap3d">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
</manifest>
package cn.qiuxiang.react.amap3d
import cn.qiuxiang.react.amap3d.maps.*
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class AMap3DPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf()
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return listOf(
AMapViewManager(),
AMapMarkerManager(),
AMapInfoWindowManager(),
AMapPolylineManager(),
AMapPolygonManager(),
AMapCircleManager()
)
}
}
package cn.qiuxiang.react.amap3d
import android.content.res.Resources
import com.amap.api.maps2d.model.LatLng
import com.amap.api.maps2d.model.LatLngBounds
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.WritableMap
fun Float.toPx(): Int {
return (this * Resources.getSystem().displayMetrics.density).toInt()
}
fun ReadableMap.toLatLng(): LatLng {
return LatLng(this.getDouble("latitude"), this.getDouble("longitude"))
}
fun ReadableArray.toLatLngList(): ArrayList<LatLng> {
return ArrayList((0..(this.size() - 1)).map { this.getMap(it).toLatLng() })
}
fun LatLng.toWritableMap(): WritableMap {
val map = Arguments.createMap()
map.putDouble("latitude", this.latitude)
map.putDouble("longitude", this.longitude)
return map
}
fun ReadableMap.toLatLngBounds(): LatLngBounds {
val latitude = this.getDouble("latitude")
val longitude = this.getDouble("longitude")
val latitudeDelta = this.getDouble("latitudeDelta")
val longitudeDelta = this.getDouble("longitudeDelta")
return LatLngBounds(
LatLng(latitude - latitudeDelta / 2, longitude - longitudeDelta / 2),
LatLng(latitude + latitudeDelta / 2, longitude + longitudeDelta / 2)
)
}
\ No newline at end of file
package cn.qiuxiang.react.amap3d.maps
import android.content.Context
import android.graphics.Color
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.model.Circle
import com.amap.api.maps2d.model.CircleOptions
import com.amap.api.maps2d.model.LatLng
import com.facebook.react.views.view.ReactViewGroup
class AMapCircle(context: Context) : ReactViewGroup(context), AMapOverlay {
private var circle: Circle? = null
var center: LatLng? = null
set(value) {
field = value
circle?.center = value
}
var radius: Double = 0.0
set(value) {
field = value
circle?.radius = value
}
var strokeWidth: Float = 1f
set(value) {
field = value
circle?.strokeWidth = value
}
var strokeColor: Int = Color.BLACK
set(value) {
field = value
circle?.strokeColor = value
}
var fillColor: Int = Color.BLACK
set(value) {
field = value
circle?.fillColor = value
}
var zIndex: Float = 0f
set(value) {
field = value
circle?.zIndex = value
}
override fun add(map: AMap) {
circle = map.addCircle(CircleOptions()
.center(center)
.radius(radius)
.strokeColor(strokeColor)
.strokeWidth(strokeWidth)
.fillColor(fillColor)
.zIndex(zIndex))
}
override fun remove() {
circle?.remove()
}
}
package cn.qiuxiang.react.amap3d.maps
import cn.qiuxiang.react.amap3d.toLatLng
import cn.qiuxiang.react.amap3d.toPx
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.uimanager.SimpleViewManager
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.annotations.ReactProp
@Suppress("unused")
internal class AMapCircleManager : SimpleViewManager<AMapCircle>() {
override fun getName(): String {
return "AMapCircle"
}
override fun createViewInstance(reactContext: ThemedReactContext): AMapCircle {
return AMapCircle(reactContext)
}
@ReactProp(name = "coordinate")
fun setCoordinate(circle: AMapCircle, coordinate: ReadableMap) {
circle.center = coordinate.toLatLng()
}
@ReactProp(name = "radius")
fun setRadius(circle: AMapCircle, radius: Double) {
circle.radius = radius
}
@ReactProp(name = "fillColor", customType = "Color")
fun setFillColor(circle: AMapCircle, fillColor: Int) {
circle.fillColor = fillColor
}
@ReactProp(name = "strokeColor", customType = "Color")
fun setStrokeColor(circle: AMapCircle, strokeColor: Int) {
circle.strokeColor = strokeColor
}
@ReactProp(name = "strokeWidth")
fun setStrokeWidth(circle: AMapCircle, strokeWidth: Float) {
circle.strokeWidth = strokeWidth.toPx().toFloat()
}
@ReactProp(name = "zIndex")
fun setZIndez(circle: AMapCircle, zIndex: Float) {
circle.zIndex = zIndex
}
}
package cn.qiuxiang.react.amap3d.maps
import android.content.Context
import com.facebook.react.views.view.ReactViewGroup
class AMapInfoWindow(context: Context) : ReactViewGroup(context) {
init {
addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
val layoutParams = this.layoutParams
if (layoutParams == null || layoutParams.width != this.width || layoutParams.height != this.height) {
this.layoutParams = LayoutParams(this.width, this.height)
}
}
}
}
\ No newline at end of file
package cn.qiuxiang.react.amap3d.maps
import android.content.Context
import android.graphics.Color
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.model.Marker
class AMapInfoWindowAdapter(
private val context: Context,
private val markers: HashMap<String, AMapMarker>
) : AMap.InfoWindowAdapter {
val paddingTop = context.resources.displayMetrics.density
override fun getInfoWindow(marker: Marker): View? {
return markers[marker.id]?.infoWindow
}
override fun getInfoContents(marker: Marker): View? {
val layout = LinearLayout(context)
layout.orientation = LinearLayout.VERTICAL
val titleView = TextView(context)
titleView.text = marker.title
titleView.setTextColor(Color.parseColor("#212121"))
layout.addView(titleView)
val snippet = marker.snippet
if (!snippet.isEmpty()) {
val snippetView = TextView(context)
snippetView.text = snippet
snippetView.maxEms = 12
snippetView.setPadding(0, paddingTop.toInt(), 0, 0)
snippetView.setTextColor(Color.parseColor("#757575"))
layout.addView(snippetView)
}
return layout
}
}
package cn.qiuxiang.react.amap3d.maps
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.ViewGroupManager
class AMapInfoWindowManager : ViewGroupManager<AMapInfoWindow>() {
override fun getName(): String {
return "AMapInfoWindow"
}
override fun createViewInstance(reactContext: ThemedReactContext): AMapInfoWindow {
return AMapInfoWindow(reactContext)
}
}
\ No newline at end of file
package cn.qiuxiang.react.amap3d.maps
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.view.View
import cn.qiuxiang.react.amap3d.toPx
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.model.*
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.views.view.ReactViewGroup
class AMapMarker(context: Context) : ReactViewGroup(context), AMapOverlay {
companion object {
private val COLORS = mapOf(
"AZURE" to BitmapDescriptorFactory.HUE_AZURE,
"BLUE" to BitmapDescriptorFactory.HUE_BLUE,
"CYAN" to BitmapDescriptorFactory.HUE_CYAN,
"GREEN" to BitmapDescriptorFactory.HUE_GREEN,
"MAGENTA" to BitmapDescriptorFactory.HUE_MAGENTA,
"ORANGE" to BitmapDescriptorFactory.HUE_ORANGE,
"RED" to BitmapDescriptorFactory.HUE_RED,
"ROSE" to BitmapDescriptorFactory.HUE_ROSE,
"VIOLET" to BitmapDescriptorFactory.HUE_VIOLET,
"YELLOW" to BitmapDescriptorFactory.HUE_YELLOW
)
}
private var icon: View? = null
private var bitmapDescriptor: BitmapDescriptor? = null
private var anchorU: Float = 0.5f
private var anchorV: Float = 1f
var infoWindow: AMapInfoWindow? = null
var marker: Marker? = null
private set
var position: LatLng? = null
set(value) {
field = value
marker?.position = value
}
var zIndex: Float = 0.0f
set(value) {
field = value
marker?.zIndex = value
}
var title = ""
set(value) {
field = value
marker?.title = value
}
var snippet = ""
set(value) {
field = value
marker?.snippet = value
}
var draggable: Boolean = false
set(value) {
field = value
marker?.isDraggable = value
}
var active: Boolean = false
set(value) {
field = value
if (value) {
marker?.showInfoWindow()
} else {
marker?.hideInfoWindow()
}
}
override fun addView(child: View, index: Int) {
super.addView(child, index)
icon = child
icon?.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> updateIcon() }
}
override fun add(map: AMap) {
marker = map.addMarker(MarkerOptions()
.icon(bitmapDescriptor)
.draggable(draggable)
.position(position)
.anchor(anchorU, anchorV)
.title(title)
.snippet(snippet)
.zIndex(zIndex))
this.active = active
}
override fun remove() {
marker?.destroy()
}
fun setIconColor(icon: String) {
bitmapDescriptor = COLORS[icon.toUpperCase()]?.let {
BitmapDescriptorFactory.defaultMarker(it)
}
marker?.setIcon(bitmapDescriptor)
}
fun updateIcon() {
icon?.let {
if (it.width != 0 && it.height != 0) {
val bitmap = Bitmap.createBitmap(
it.width, it.height, Bitmap.Config.ARGB_8888)
it.draw(Canvas(bitmap))
bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap)
marker?.setIcon(bitmapDescriptor)
}
}
}
fun setImage(name: String) {
val drawable = context.resources.getIdentifier(name, "drawable", context.packageName)
bitmapDescriptor = BitmapDescriptorFactory.fromResource(drawable)
marker?.setIcon(bitmapDescriptor)
}
fun setAnchor(x: Double, y: Double) {
anchorU = x.toFloat()
anchorV = y.toFloat()
marker?.setAnchor(anchorU, anchorV)
}
fun lockToScreen(args: ReadableArray?) {
if (args != null) {
val x = args.getDouble(0).toFloat().toPx()
val y = args.getDouble(1).toFloat().toPx()
marker?.setPositionByPixels(x, y)
}
}
}
package cn.qiuxiang.react.amap3d.maps
import android.view.View
import cn.qiuxiang.react.amap3d.toLatLng
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.common.MapBuilder
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.ViewGroupManager
import com.facebook.react.uimanager.annotations.ReactProp
@Suppress("unused")
internal class AMapMarkerManager : ViewGroupManager<AMapMarker>() {
override fun getName(): String {
return "AMapMarker"
}
override fun createViewInstance(reactContext: ThemedReactContext): AMapMarker {
return AMapMarker(reactContext)
}
override fun addView(marker: AMapMarker, view: View, index: Int) {
when (view) {
is AMapInfoWindow -> marker.infoWindow = view
else -> super.addView(marker, view, index)
}
}
override fun getExportedCustomDirectEventTypeConstants(): Map<String, Any>? {
return MapBuilder.of(
"onPress", MapBuilder.of("registrationName", "onPress"),
"onDragStart", MapBuilder.of("registrationName", "onDragStart"),
"onDrag", MapBuilder.of("registrationName", "onDrag"),
"onDragEnd", MapBuilder.of("registrationName", "onDragEnd"),
"onInfoWindowPress", MapBuilder.of("registrationName", "onInfoWindowPress")
)
}
companion object {
val UPDATE = 1
val ACTIVE = 2
val LOCK_TO_SCREEN = 3
}
override fun getCommandsMap(): Map<String, Int> {
return mapOf(
"update" to UPDATE,
"active" to ACTIVE,
"lockToScreen" to LOCK_TO_SCREEN
)
}
override fun receiveCommand(marker: AMapMarker, commandId: Int, args: ReadableArray?) {
when (commandId) {
UPDATE -> marker.updateIcon()
ACTIVE -> marker.active = true
LOCK_TO_SCREEN -> marker.lockToScreen(args)
}
}
@ReactProp(name = "title")
fun setTitle(marker: AMapMarker, title: String) {
marker.title = title
}
@ReactProp(name = "description")
fun setSnippet(marker: AMapMarker, description: String) {
marker.snippet = description
}
@ReactProp(name = "coordinate")
fun setCoordinate(view: AMapMarker, coordinate: ReadableMap) {
view.position = coordinate.toLatLng()
}
@ReactProp(name = "draggable")
fun setDraggable(marker: AMapMarker, draggable: Boolean) {
marker.draggable = draggable
}
@ReactProp(name = "active")
fun setSelected(marker: AMapMarker, active: Boolean) {
marker.active = active
}
@ReactProp(name = "color")
fun setIcon(marker: AMapMarker, icon: String) {
marker.setIconColor(icon)
}
@ReactProp(name = "image")
fun setImage(marker: AMapMarker, image: String) {
marker.setImage(image)
}
@ReactProp(name = "zIndex")
fun setZIndez(marker: AMapMarker, zIndex: Float) {
marker.zIndex = zIndex
}
@ReactProp(name = "anchor")
fun setAnchor(view: AMapMarker, coordinate: ReadableMap) {
view.setAnchor(coordinate.getDouble("x"), coordinate.getDouble("y"))
}
}
package cn.qiuxiang.react.amap3d.maps
import com.amap.api.maps2d.AMap
interface AMapOverlay {
fun add(map: AMap)
fun remove()
}
\ No newline at end of file
package cn.qiuxiang.react.amap3d.maps
import android.content.Context
import android.graphics.Color
import cn.qiuxiang.react.amap3d.toLatLngList
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.model.LatLng
import com.amap.api.maps2d.model.Polygon
import com.amap.api.maps2d.model.PolygonOptions
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.views.view.ReactViewGroup
class AMapPolygon(context: Context) : ReactViewGroup(context), AMapOverlay {
private var polygon: Polygon? = null
private var coordinates: ArrayList<LatLng> = ArrayList()
var strokeWidth: Float = 1f
set(value) {
field = value
polygon?.strokeWidth = value
}
var strokeColor: Int = Color.BLACK
set(value) {
field = value
polygon?.strokeColor = value
}
var fillColor: Int = Color.BLACK
set(value) {
field = value
polygon?.fillColor = value
}
var zIndex: Float = 0f
set(value) {
field = value
polygon?.zIndex = value
}
fun setCoordinates(coordinates: ReadableArray) {
this.coordinates = coordinates.toLatLngList()
polygon?.points = this.coordinates
}
override fun add(map: AMap) {
polygon = map.addPolygon(PolygonOptions()
.addAll(coordinates)
.strokeColor(strokeColor)
.strokeWidth(strokeWidth)
.fillColor(fillColor)
.zIndex(zIndex))
}
override fun remove() {
polygon?.remove()
}
}
package cn.qiuxiang.react.amap3d.maps
import cn.qiuxiang.react.amap3d.toPx
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.uimanager.SimpleViewManager
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.annotations.ReactProp
@Suppress("unused")
internal class AMapPolygonManager : SimpleViewManager<AMapPolygon>() {
override fun getName(): String {
return "AMapPolygon"
}
override fun createViewInstance(reactContext: ThemedReactContext): AMapPolygon {
return AMapPolygon(reactContext)
}
@ReactProp(name = "coordinates")
fun setCoordinate(polygon: AMapPolygon, coordinates: ReadableArray) {
polygon.setCoordinates(coordinates)
}
@ReactProp(name = "fillColor", customType = "Color")
fun setFillColor(polygon: AMapPolygon, fillColor: Int) {
polygon.fillColor = fillColor
}
@ReactProp(name = "strokeColor", customType = "Color")
fun setStrokeColor(polygon: AMapPolygon, strokeColor: Int) {
polygon.strokeColor = strokeColor
}
@ReactProp(name = "strokeWidth")
fun setStrokeWidth(polygon: AMapPolygon, strokeWidth: Float) {
polygon.strokeWidth = strokeWidth.toPx().toFloat()
}
@ReactProp(name = "zIndex")
fun setZindex(polygon: AMapPolygon, zIndex: Float) {
polygon.zIndex = zIndex
}
}
package cn.qiuxiang.react.amap3d.maps
import android.content.Context
import android.graphics.Color
import cn.qiuxiang.react.amap3d.toLatLngList
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.model.LatLng
import com.amap.api.maps2d.model.Polyline
import com.amap.api.maps2d.model.PolylineOptions
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.views.view.ReactViewGroup
class AMapPolyline(context: Context) : ReactViewGroup(context), AMapOverlay {
var polyline: Polyline? = null
private set
private var coordinates: ArrayList<LatLng> = ArrayList()
private var colors: ArrayList<Int> = ArrayList()
var width: Float = 1f
set(value) {
field = value
polyline?.width = value
}
var color: Int = Color.BLACK
set(value) {
field = value
polyline?.color = value
}
var zIndex: Float = 0f
set(value) {
field = value
polyline?.zIndex = value
}
var geodesic: Boolean = false
set(value) {
field = value
polyline?.isGeodesic = value
}
var dashed: Boolean = false
set(value) {
field = value
polyline?.isDottedLine = value
}
var gradient: Boolean = false
fun setCoordinates(coordinates: ReadableArray) {
this.coordinates = coordinates.toLatLngList()
polyline?.points = this.coordinates
}
fun setColors(colors: ReadableArray) {
this.colors = ArrayList((0 until colors.size()).map { colors.getInt(it) })
}
override fun add(map: AMap) {
polyline = map.addPolyline(PolylineOptions()
.addAll(coordinates)
.color(color)
.width(width)
.geodesic(geodesic)
.setDottedLine(dashed)
.zIndex(zIndex))
}
override fun remove() {
polyline?.remove()
}
}
package cn.qiuxiang.react.amap3d.maps
import cn.qiuxiang.react.amap3d.toPx
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.uimanager.SimpleViewManager
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.annotations.ReactProp
@Suppress("unused")
internal class AMapPolylineManager : SimpleViewManager<AMapPolyline>() {
override fun getName(): String {
return "AMapPolyline"
}
override fun createViewInstance(reactContext: ThemedReactContext): AMapPolyline {
return AMapPolyline(reactContext)
}
override fun getExportedCustomDirectEventTypeConstants(): Map<String, Any> {
return mapOf("onPress" to mapOf("registrationName" to "onPress"))
}
@ReactProp(name = "coordinates")
fun setCoordinate(polyline: AMapPolyline, coordinates: ReadableArray) {
polyline.setCoordinates(coordinates)
}
@ReactProp(name = "colors")
fun setColors(polyline: AMapPolyline, colors: ReadableArray) {
polyline.setColors(colors)
}
@ReactProp(name = "color", customType = "Color")
fun setColor(polyline: AMapPolyline, color: Int) {
polyline.color = color
}
@ReactProp(name = "width")
fun setWidth(polyline: AMapPolyline, width: Float) {
polyline.width = width.toPx().toFloat()
}
@ReactProp(name = "zIndex")
fun setZIndex_(polyline: AMapPolyline, zIndex: Float) {
polyline.zIndex = zIndex
}
@ReactProp(name = "geodesic")
fun setGeodesic(polyline: AMapPolyline, geodesic: Boolean) {
polyline.geodesic = geodesic
}
@ReactProp(name = "dashed")
fun setDashed(polyline: AMapPolyline, dashed: Boolean) {
polyline.dashed = dashed
}
@ReactProp(name = "gradient")
fun setGradient(polyline: AMapPolyline, gradient: Boolean) {
polyline.gradient = gradient
}
}
package cn.qiuxiang.react.amap3d.maps
import android.content.Context
import android.view.MotionEvent
import android.view.View
import cn.qiuxiang.react.amap3d.toLatLng
import cn.qiuxiang.react.amap3d.toLatLngBounds
import cn.qiuxiang.react.amap3d.toWritableMap
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.CameraUpdateFactory
import com.amap.api.maps2d.MapView
import com.amap.api.maps2d.model.BitmapDescriptorFactory
import com.amap.api.maps2d.model.CameraPosition
import com.amap.api.maps2d.model.Marker
import com.amap.api.maps2d.model.MyLocationStyle
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.WritableMap
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.events.RCTEventEmitter
class AMapView(context: Context) : MapView(context) {
private val eventEmitter: RCTEventEmitter = (context as ThemedReactContext).getJSModule(RCTEventEmitter::class.java)
private val markers = HashMap<String, AMapMarker>()
private val lines = HashMap<String, AMapPolyline>()
var touchEnable: Boolean = true
private val locationStyle by lazy {
val locationStyle = MyLocationStyle()
locationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER)
locationStyle
}
init {
super.onCreate(null)
map.setOnMapClickListener { latLng ->
for (marker in markers.values) {
marker.active = false
}
emit(id, "onMapPress", latLng.toWritableMap())
}
map.setOnMapLongClickListener { latLng ->
emit(id, "onLongPress", latLng.toWritableMap())
}
map.setOnMyLocationChangeListener { location ->
val event = Arguments.createMap()
event.putDouble("latitude", location.latitude)
event.putDouble("longitude", location.longitude)
event.putDouble("accuracy", location.accuracy.toDouble())
event.putDouble("altitude", location.altitude)
event.putDouble("speed", location.speed.toDouble())
event.putInt("timestamp", location.time.toInt())
emit(id, "onLocation", event)
}
map.setOnMarkerClickListener { marker ->
markers[marker.id]?.let {
it.active = true
emit(it.id, "onPress")
}
true
}
map.setOnMarkerDragListener(object : AMap.OnMarkerDragListener {
override fun onMarkerDragStart(marker: Marker) {
emit(markers[marker.id]?.id, "onDragStart")
}
override fun onMarkerDrag(marker: Marker) {
emit(markers[marker.id]?.id, "onDrag")
}
override fun onMarkerDragEnd(marker: Marker) {
emit(markers[marker.id]?.id, "onDragEnd", marker.position.toWritableMap())
}
})
map.setOnCameraChangeListener(object : AMap.OnCameraChangeListener {
override fun onCameraChangeFinish(position: CameraPosition?) {
emitCameraChangeEvent("onStatusChangeComplete", position)
}
override fun onCameraChange(position: CameraPosition?) {
emitCameraChangeEvent("onStatusChange", position)
}
})
map.setOnInfoWindowClickListener { marker ->
emit(markers[marker.id]?.id, "onInfoWindowPress")
}
map.setInfoWindowAdapter(AMapInfoWindowAdapter(context, markers))
}
fun emitCameraChangeEvent(event: String, position: CameraPosition?) {
position?.let {
val data = it.target.toWritableMap()
data.putDouble("zoomLevel", it.zoom.toDouble())
data.putDouble("tilt", it.tilt.toDouble())
data.putDouble("rotation", it.bearing.toDouble())
if (event == "onStatusChangeComplete") {
val southwest = map.projection.visibleRegion.latLngBounds.southwest
val northeast = map.projection.visibleRegion.latLngBounds.northeast
data.putDouble("latitudeDelta", Math.abs(southwest.latitude - northeast.latitude))
data.putDouble("longitudeDelta", Math.abs(southwest.longitude - northeast.longitude))
}
emit(id, event, data)
}
}
fun emit(id: Int?, name: String, data: WritableMap = Arguments.createMap()) {
id?.let { eventEmitter.receiveEvent(it, name, data) }
}
fun add(child: View) {
if (child is AMapOverlay) {
child.add(map)
if (child is AMapMarker) {
markers[child.marker?.id!!] = child
}
if (child is AMapPolyline) {
lines[child.polyline?.id!!] = child
}
}
}
fun remove(child: View) {
if (child is AMapOverlay) {
child.remove()
if (child is AMapMarker) {
markers.remove(child.marker?.id)
}
if (child is AMapPolyline) {
lines.remove(child.polyline?.id)
}
}
}
private val animateCallback = object : AMap.CancelableCallback {
override fun onCancel() {
emit(id, "onAnimateCancel")
}
override fun onFinish() {
emit(id, "onAnimateFinish")
}
}
fun animateTo(args: ReadableArray?) {
val currentCameraPosition = map.cameraPosition
val target = args?.getMap(0)!!
val duration = args.getInt(1)
var coordinate = currentCameraPosition.target
var zoomLevel = currentCameraPosition.zoom
var tilt = currentCameraPosition.tilt
var rotation = currentCameraPosition.bearing
if (target.hasKey("coordinate")) {
coordinate = target.getMap("coordinate").toLatLng()
}
if (target.hasKey("zoomLevel")) {
zoomLevel = target.getDouble("zoomLevel").toFloat()
}
if (target.hasKey("tilt")) {
tilt = target.getDouble("tilt").toFloat()
}
if (target.hasKey("rotation")) {
rotation = target.getDouble("rotation").toFloat()
}
val cameraUpdate = CameraUpdateFactory.newCameraPosition(
CameraPosition(coordinate, zoomLevel, tilt, rotation))
map.animateCamera(cameraUpdate, duration.toLong(), animateCallback)
}
fun setRegion(region: ReadableMap) {
map.moveCamera(CameraUpdateFactory.newLatLngBounds(region.toLatLngBounds(), 0))
}
fun setLocationEnabled(enabled: Boolean) {
map.isMyLocationEnabled = enabled
map.setMyLocationStyle(locationStyle)
}
fun setLocationInterval(interval: Long) {
locationStyle.interval(interval)
}
fun setLocationStyle(style: ReadableMap) {
if (style.hasKey("fillColor")) {
locationStyle.radiusFillColor(style.getInt("fillColor"))
}
if (style.hasKey("strokeColor")) {
locationStyle.strokeColor(style.getInt("strokeColor"))
}
if (style.hasKey("strokeWidth")) {
locationStyle.strokeWidth(style.getDouble("strokeWidth").toFloat())
}
if (style.hasKey("image")) {
val drawable = context.resources.getIdentifier(
style.getString("image"), "drawable", context.packageName)
locationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(drawable))
}
}
fun setLocationType(type: Int) {
locationStyle.myLocationType(type)
map.setMyLocationStyle(locationStyle)
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
return !touchEnable
}
}
package cn.qiuxiang.react.amap3d.maps
import android.view.View
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.CameraUpdateFactory
import com.amap.api.maps2d.model.LatLng
import com.amap.api.maps2d.model.MyLocationStyle
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.common.MapBuilder
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.ViewGroupManager
import com.facebook.react.uimanager.annotations.ReactProp
@Suppress("unused")
internal class AMapViewManager : ViewGroupManager<AMapView>() {
companion object {
val ANIMATE_TO = 1
}
override fun getName(): String {
return "AMapView"
}
override fun createViewInstance(reactContext: ThemedReactContext): AMapView {
return AMapView(reactContext)
}
override fun onDropViewInstance(view: AMapView) {
super.onDropViewInstance(view)
view.onDestroy()
}
override fun getCommandsMap(): Map<String, Int> {
return mapOf("animateTo" to ANIMATE_TO)
}
override fun receiveCommand(overlay: AMapView, commandId: Int, args: ReadableArray?) {
when (commandId) {
ANIMATE_TO -> overlay.animateTo(args)
}
}
override fun addView(mapView: AMapView, child: View, index: Int) {
mapView.add(child)
super.addView(mapView, child, index)
}
override fun removeViewAt(parent: AMapView, index: Int) {
parent.remove(parent.getChildAt(index))
super.removeViewAt(parent, index)
}
override fun getExportedCustomDirectEventTypeConstants(): Map<String, Any> {
return MapBuilder.of(
"onMapPress", MapBuilder.of("registrationName", "onMapPress"),
"onLongPress", MapBuilder.of("registrationName", "onLongPress"),
"onAnimateCancel", MapBuilder.of("registrationName", "onAnimateCancel"),
"onAnimateFinish", MapBuilder.of("registrationName", "onAnimateFinish"),
"onStatusChange", MapBuilder.of("registrationName", "onStatusChange"),
"onStatusChangeComplete", MapBuilder.of("registrationName", "onStatusChangeComplete"),
"onLocation", MapBuilder.of("registrationName", "onLocation")
)
}
@ReactProp(name = "locationEnabled")
fun setMyLocationEnabled(view: AMapView, enabled: Boolean) {
view.setLocationEnabled(enabled)
}
@ReactProp(name = "showsCompass")
fun setCompassEnabled(view: AMapView, show: Boolean) {
view.map.uiSettings.isCompassEnabled = show
}
@ReactProp(name = "showsZoomControls")
fun setZoomControlsEnabled(view: AMapView, enabled: Boolean) {
view.map.uiSettings.isZoomControlsEnabled = enabled
}
@ReactProp(name = "showsScale")
fun setScaleControlsEnabled(view: AMapView, enabled: Boolean) {
view.map.uiSettings.isScaleControlsEnabled = enabled
}
@ReactProp(name = "showsLocationButton")
fun setMyLocationButtonEnabled(view: AMapView, enabled: Boolean) {
view.map.uiSettings.isMyLocationButtonEnabled = enabled
}
@ReactProp(name = "showsTraffic")
fun setTrafficEnabled(view: AMapView, enabled: Boolean) {
view.map.isTrafficEnabled = enabled
}
@ReactProp(name = "zoomLevel")
fun setZoomLevel(view: AMapView, zoomLevel: Float) {
view.map.moveCamera(CameraUpdateFactory.zoomTo(zoomLevel))
}
@ReactProp(name = "mapType")
fun setMapType(view: AMapView, mapType: String) {
when (mapType) {
"standard" -> view.map.mapType = AMap.MAP_TYPE_NORMAL
"satellite" -> view.map.mapType = AMap.MAP_TYPE_SATELLITE
}
}
@ReactProp(name = "zoomEnabled")
fun setZoomGesturesEnabled(view: AMapView, enabled: Boolean) {
view.map.uiSettings.isZoomGesturesEnabled = enabled
}
@ReactProp(name = "scrollEnabled")
fun setScrollGesturesEnabled(view: AMapView, enabled: Boolean) {
view.map.uiSettings.isScrollGesturesEnabled = enabled
}
@ReactProp(name = "coordinate")
fun moveToCoordinate(view: AMapView, coordinate: ReadableMap) {
view.map.moveCamera(CameraUpdateFactory.changeLatLng(LatLng(
coordinate.getDouble("latitude"),
coordinate.getDouble("longitude"))))
}
@ReactProp(name = "region")
fun setRegion(view: AMapView, region: ReadableMap) {
view.setRegion(region)
}
@ReactProp(name = "locationInterval")
fun setLocationInterval(view: AMapView, interval: Int) {
view.setLocationInterval(interval.toLong())
}
@ReactProp(name = "locationStyle")
fun setLocationStyle(view: AMapView, style: ReadableMap) {
view.setLocationStyle(style)
}
@ReactProp(name = "touchEnable")
fun setViewTouchEnable(view: AMapView, enabled: Boolean){
view.touchEnable = enabled
}
@ReactProp(name = "locationType")
fun setLocationStyle(view: AMapView, type: String) {
when (type) {
"show" -> view.setLocationType(MyLocationStyle.LOCATION_TYPE_SHOW)
"locate" -> view.setLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
"follow" -> view.setLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW)"follow_no_center" -> view.setLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER)
}
}
}
/**
* 基础组件,包含一些公共方法
*
* @flow
*/
import { PureComponent } from 'react'
import { findNodeHandle, UIManager } from 'react-native'
export default class Component<T> extends PureComponent<T> {
/**
* 原生组件名称
*/
name: string
/**
* 调用原生方法
*
* @private
*/
sendCommand(command: string, params?: any[]) {
UIManager.dispatchViewManagerCommand(
findNodeHandle(this),
UIManager[this.name].Commands[command],
params,
)
}
}
import PropTypes from 'prop-types'
const LatLng = PropTypes.shape({
latitude: PropTypes.number.isRequired,
longitude: PropTypes.number.isRequired,
})
const Region = PropTypes.shape({
latitude: PropTypes.number.isRequired,
longitude: PropTypes.number.isRequired,
latitudeDelta: PropTypes.number.isRequired,
longitudeDelta: PropTypes.number.isRequired,
})
const Point = PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
})
export { LatLng, Region, Point }
import MapView from './maps/MapView'
import Marker from './maps/Marker'
import Polygon from './maps/Polygon'
import Circle from './maps/Circle'
MapView.Marker = Marker
MapView.Polygon = Polygon
MapView.Circle = Circle
export default MapView
export {
MapView,
Marker,
Polygon,
Circle,
}
// import MapView from './maps/MapView'
// import Marker from './maps/Marker'
// import Polygon from './maps/Polygon'
// import Circle from './maps/Circle'
import { Map, Marker as RMarker } from 'react-amap';
const MapView = (props) => {
return <Map {...props} center={props.coordinate}></Map>
}
const Marker = (props) => {
return <RMarker {...props} center={props.coordinate} />
}
MapView.Marker = Marker
export default MapView
export {
MapView,
Marker,
}
import PropTypes from 'prop-types'
import { ColorPropType, requireNativeComponent, ViewPropTypes } from 'react-native'
import { LatLng } from '../PropTypes'
export default requireNativeComponent('AMapCircle', {
propTypes: {
...ViewPropTypes,
/**
* 圆点坐标
*/
coordinate: LatLng.isRequired,
/**
* 半径(米)
*/
radius: PropTypes.number.isRequired,
/**
* 边线宽度
*/
strokeWidth: PropTypes.number,
/**
* 边线颜色
*/
strokeColor: ColorPropType,
/**
* 填充颜色
*/
fillColor: ColorPropType,
/**
* 层级
*/
zIndex: PropTypes.number,
},
})
// @flow
import React from 'react'
import PropTypes from 'prop-types'
import { processColor, requireNativeComponent, ViewPropTypes, Platform } from 'react-native'
import { LatLng, Region } from '../PropTypes'
import Component from '../Component'
export type MapStatus = {
zoomLevel?: number,
coordinate?: LatLng,
titl?: number,
rotation?: number,
}
export const LocationStyle = PropTypes.shape({
image: PropTypes.string,
fillColor: PropTypes.string,
strokeColor: PropTypes.string,
strokeWidth: PropTypes.number,
})
const isIos = Platform.OS === 'ios'
export default class MapView extends Component<any> {
static propTypes = {
...ViewPropTypes,
/**
* 地图类型
*
* - standard: 标准地图
* - satellite: 卫星地图
* - navigation: 导航地图
* - night: 夜间地图
* - bus: 公交地图
*/
mapType: PropTypes.oneOf(['standard', 'satellite', 'navigation', 'night', 'bus']),
/**
* 是否启用跟踪模式
* 0: 不跟踪
* 1: 跟踪用户定位
* 2: 跟踪用户定位和方向
*/
userTrackingMode: PropTypes.oneOf(0, 1, 2),
/**
* 是否跟踪用户位置
*/
showsUserLocation: PropTypes.bool,
/**
* 缩放尺寸,范围是:[3-19]
*/
zoomLevel: PropTypes.number,
/**
* 设置定位图标的样式
*/
locationStyle: LocationStyle,
/**
* 设置定位模式 默认 LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER
*
* @platform android
*/
locationType: PropTypes.oneOf(['show', 'locate', 'follow', 'map_rotate', 'location_rotate',
'location_rotate_no_center', 'follow_no_center', 'map_rotate_no_center']),
/**
* 是否启用定位
*/
locationEnabled: PropTypes.bool,
/**
* 定位间隔(ms),默认 2000
*
* @platform android
*/
locationInterval: PropTypes.number,
/**
* 定位的最小更新距离
*
* @platform ios
*/
distanceFilter: PropTypes.number,
/**
* 是否显示室内地图
*/
showsIndoorMap: PropTypes.bool,
/**
* 是否显示室内地图楼层切换控件
*
* TODO: 似乎并不能正常显示
*/
showsIndoorSwitch: PropTypes.bool,
/**
* 是否显示3D建筑
*/
showsBuildings: PropTypes.bool,
/**
* 是否显示文本标签
*/
showsLabels: PropTypes.bool,
/**
* 是否显示指南针
*/
showsCompass: PropTypes.bool,
/**
* 是否显示放大缩小按钮
*
* @platform android
*/
showsZoomControls: PropTypes.bool,
/**
* 是否显示比例尺
*/
showsScale: PropTypes.bool,
/**
* 是否显示定位按钮
*
* @platform android
*/
showsLocationButton: PropTypes.bool,
/**
* 是否显示路况
*/
showsTraffic: PropTypes.bool,
/**
* 最大缩放级别
*/
maxZoomLevel: PropTypes.number,
/**
* 最小缩放级别
*/
minZoomLevel: PropTypes.number,
/**
* 当前缩放级别,取值范围 [3, 20]
*/
zoomLevel: PropTypes.number,
/**
* 中心坐标
*/
coordinate: LatLng,
/**
* 显示区域
*/
region: Region,
/**
* 限制地图只能显示某个矩形区域
*/
limitRegion: Region,
/**
* 倾斜角度,取值范围 [0, 60]
*/
tilt: PropTypes.number,
/**
* 旋转角度
*/
rotation: PropTypes.number,
/**
* 是否启用缩放手势,用于放大缩小
*/
zoomEnabled: PropTypes.bool,
/**
* 是否启用滑动手势,用于平移
*/
scrollEnabled: PropTypes.bool,
/**
* 是否启用旋转手势,用于调整方向
*/
rotateEnabled: PropTypes.bool,
/**
* 是否启用倾斜手势,用于改变视角
*/
tiltEnabled: PropTypes.bool,
/**
* 是否可以触摸
*/
touchEnable: PropTypes.bool,
/**
* 是否启用定位
*/
showsUserLocation: PropTypes.bool,
/**
* 中心坐标
*/
centerLocation: LatLng,
/**
* 点击事件
*
* @param {{ nativeEvent: LatLng }}
*/
onMapPress: PropTypes.func,
/**
* 长按事件
*
* @param {{ nativeEvent: LatLng }}
*/
onLongPress: PropTypes.func,
/**
* 定位事件
*
* @param {{
* nativeEvent: {
* timestamp: number,
* speed: number,
* accuracy: number,
* altitude: number,
* longitude: number,
* latitude: number,
* }
* }}
*/
onLocation: PropTypes.func,
/**
* 动画完成事件
*/
onAnimateFinish: PropTypes.func,
/**
* 动画取消事件
*/
onAnimateCancel: PropTypes.func,
/**
* 地图状态变化事件
*
* @param {{
* nativeEvent: {
* longitude: number,
* latitude: number,
* rotation: number,
* zoomLevel: number,
* tilt: number,
* }
* }}
*/
onStatusChange: PropTypes.func,
/**
* 地图状态变化完成事件
*
* @param {{
* nativeEvent: {
* longitude: number,
* latitude: number,
* longitudeDelta: number,
* latitudeDelta: number,
* rotation: number,
* zoomLevel: number,
* tilt: number,
* }
* }}
*/
onStatusChangeComplete: PropTypes.func,
}
name = 'AMapView'
isMapFirstLoaded = false
_isMoveByUser = true
lastCompleteTime = 0
_onMoveComplete = (event) => {
const oldLastCompleteTime = this.lastCompleteTime
this.lastCompleteTime = new Date().getTime()
if ((this.lastCompleteTime - oldLastCompleteTime) < 700) {
this._isMoveByUser = true
return
}
if (isIos && !this.isMapFirstLoaded) {
this.isMapFirstLoaded = true
this._isMoveByUser = true
return
}
this.props.onStatusChangeComplete && this.props.onStatusChangeComplete(event, this._isMoveByUser)
this._isMoveByUser = true
}
componentWillReceiveProps({ coordinate }) {
const oldCoordinate = this.props.coordinate
if (coordinate && oldCoordinate) {
const { latitude, longitude } = coordinate
const oldLatitude = oldCoordinate.latitude
const oldLongitude = oldCoordinate.longitude
if ((latitude != oldLatitude) && (longitude != oldLongitude)) {
this._isMoveByUser = false
}
} else if (coordinate) {
this._isMoveByUser = false
}
}
_onMovingChange = (event) => {
if (isIos && !this.isMapFirstLoaded) {
return
}
this.props.onStatusChange && this.props.onStatusChange(event, this._isMoveByUser)
}
/**
* 动画过渡到某个状态(坐标、缩放级别、倾斜度、旋转角度)
*/
animateTo(target: MapStatus, duration?: number = 500) {
this.sendCommand('animateTo', [target, duration])
}
onMapPress = (event) => {
if (this.props.onMapPress) {
this.props.onMapPress(event)
}
}
render() {
const props = { ...this.props }
const { centerLocation } = this.props
if (centerLocation) {
delete props.centerLocation
props.coordinate = centerLocation
}
if (props.locationStyle) {
if (props.locationStyle.strokeColor) {
props.locationStyle.strokeColor = processColor(props.locationStyle.strokeColor)
}
if (props.locationStyle.fillColor) {
props.locationStyle.fillColor = processColor(props.locationStyle.fillColor)
}
}
return <AMapView {...props} onMapPress={this.onMapPress} onStatusChange={this._onMovingChange} onStatusChangeComplete={this._onMoveComplete} />
}
}
const AMapView = requireNativeComponent('AMapView', MapView)
// @flow
import React from 'react'
import PropTypes from 'prop-types'
import { Platform, requireNativeComponent, StyleSheet, ViewPropTypes, View } from 'react-native'
import { LatLng, Point } from '../PropTypes'
import Component from '../Component'
const style = StyleSheet.create({
overlay: {
position: 'absolute',
},
})
export default class Marker extends Component<any> {
static propTypes = {
...ViewPropTypes,
/**
* key
*/
markKey: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
/**
* 坐标
*/
coordinate: LatLng.isRequired,
/**
* 标题,作为默认的选中弹出显示
*/
title: PropTypes.string,
/**
* 描述,显示在标题下方
*/
description: PropTypes.string,
/**
* 默认图标颜色
*/
color: Platform.select({
android: PropTypes.oneOf([
'azure',
'blue',
'cyan',
'green',
'magenta',
'orange',
'red',
'rose',
'violet',
'yellow',
]),
ios: PropTypes.oneOf([
'red',
'green',
'purple',
]),
}),
/**
* 自定义图标
*/
icon: PropTypes.func,
/**
* 自定义图片,对应原生图片名称
*/
image: PropTypes.string,
/**
* 透明度 [0, 1]
*/
opacity: PropTypes.number,
/**
* 是否可拖拽
*/
draggable: PropTypes.bool,
/**
* 是否平贴地图
*/
flat: PropTypes.bool,
/**
* 层级
*/
zIndex: PropTypes.number,
/**
* 覆盖物锚点比例
*
* @link http://a.amap.com/lbs/static/unzip/Android_Map_Doc/3D/com/amap/api/maps/model/Marker.html#setAnchor-float-float-
* @platform android
*/
anchor: Point,
/**
* 覆盖物偏移位置
*
* @link http://a.amap.com/lbs/static/unzip/iOS_Map_Doc/AMap_iOS_API_Doc_3D/interface_m_a_annotation_view.html#a78f23c1e6a6d92faf12a00877ac278a7
* @platform ios
*/
centerOffset: Point,
/**
* 是否选中,选中时将显示信息窗体,一个地图只能有一个正在选中的 marker
*/
active: PropTypes.bool,
/**
* 是否禁用点击,默认不禁用
*/
clickDisabled: PropTypes.bool,
/**
* 是否禁用弹出窗口,默认不禁用
*/
infoWindowDisabled: PropTypes.bool,
/**
* 点击事件
*/
onPress: PropTypes.func,
/**
* 拖放开始事件
*/
onDragStart: PropTypes.func,
/**
* 拖放进行事件,类似于 mousemove,在结束之前会不断调用
*/
onDrag: PropTypes.func,
/**
* 拖放结束事件,最终坐标将传入参数
*/
onDragEnd: PropTypes.func,
/**
* 信息窗体点击事件
*
* 注意,对于自定义信息窗体,该事件是无效的
*/
onInfoWindowPress: PropTypes.func,
}
componentDidUpdate() {
if (this.icon && Platform.OS === 'android') {
setTimeout(() => this.sendCommand('update'), 0)
}
}
name = 'AMapMarker'
icon: View = null
onMarkPress = () => {
if (this.props.onPress) {
this.props.onPress(this.props.markKey)
}
}
active() {
this.sendCommand('active')
}
lockToScreen(x: number, y: number) {
this.sendCommand('lockToScreen', [x, y])
}
renderCustomMarker(icon: () => View) {
if (icon) {
this.icon = <View style={style.overlay}>{icon()}</View>
return this.icon
}
return null
}
/* eslint-disable class-methods-use-this */
renderInfoWindow(view: View) {
if (view) {
return <InfoWindow style={style.overlay}>{view}</InfoWindow>
}
return null
}
render() {
return (
<AMapMarker {...this.props} onPress={this.onMarkPress}>
{this.renderCustomMarker(this.props.icon)}
{this.renderInfoWindow(this.props.children)}
</AMapMarker>
)
}
}
const AMapMarker = requireNativeComponent('AMapMarker', Marker)
const InfoWindow = requireNativeComponent('AMapInfoWindow', {
propTypes: {
...ViewPropTypes,
},
})
import PropTypes from 'prop-types'
import { ColorPropType, requireNativeComponent, ViewPropTypes } from 'react-native'
import { LatLng } from '../PropTypes'
export default requireNativeComponent('AMapPolygon', {
propTypes: {
...ViewPropTypes,
/**
* 节点坐标
*/
coordinates: PropTypes.arrayOf(LatLng).isRequired,
/**
* 边线宽度
*/
strokeWidth: PropTypes.number,
/**
* 边线颜色
*/
strokeColor: ColorPropType,
/**
* 填充颜色
*/
fillColor: ColorPropType,
/**
* 层级
*/
zIndex: PropTypes.number,
},
})
import { NativeModules, NativeEventEmitter, DeviceEventEmitter, Platform } from 'react-native';
const locationManager = NativeModules.RNLocationManager;
const geocodeManager = NativeModules.RNGeocodeManager;
const mapNavigationManager = NativeModules.RNMapNavigationManager;
const geocodeManagerEmitter = new NativeEventEmitter(geocodeManager)
let lastId = "", promiseQueue = {}
const requestIdGenerator = (type = "geocode") => {
let requestId = `${type}-${+new Date}-${Math.ceil(Math.random() * 100000)}`
if (requestId == lastId) {
return requestIdGenerator(type)
}
lastId = requestId;
return lastId;
}
const searchRequestFactory = (type) => (...args) => {
if (geocodeManager[type]) {
let resolve, reject, promise = new Promise((res, rej) => {
resolve = res, reject = rej
}),
requestId = requestIdGenerator(type)
args = [requestId, ...args]
geocodeManager[type].apply(null, args)
promiseQueue[requestId] = { resolve, reject }
return promise
}
}
// const emitter = Platform.OS == 'ios' ? NativeAppEventEmitter : DeviceEventEmitter
geocodeManagerEmitter.addListener(
'geocode',
(reminder) => {
let {data, error, requestId} = reminder
if (requestId && promiseQueue[requestId]) {
let promise = promiseQueue[requestId];
if (error) {
promise.reject(error)
} else {
promise.resolve(data)
}
delete promiseQueue[requestId];
}
}
)
const fetchLocation = (handler) => {
if (Platform.OS === 'ios') {
locationManager.location().then(handler, (error) => {
handler(null, error);
})
}
else if (Platform.OS === 'android') {
locationManager.location();
var locationListener = DeviceEventEmitter.addListener(
'AMapLocationResultEvent',
(data) => {
var error = data.error || {}
if(error.code === 12){
// 和iOS统一`没有权限`的错误码返回
data.error.code = 'authorized_deny'
}
if (typeof handler === 'function') {
handler(data, data.error);
}
locationManager.stopLocation();
locationListener.remove();
}
);
}
}
const mapNavigation = (info)=>{
mapNavigationManager.mapNavigation(info)
}
module.exports.fetchLocation = fetchLocation;
module.exports.searchRequestFactory = searchRequestFactory;
module.exports.mapNavigation = mapNavigation;
\ No newline at end of file
let src = null;
const setAmapKey = (key, plugin = 'AMap.Geocoder') => {
src = `//webapi.amap.com/maps?v=1.3&key=${key}&plugin=${plugin}`;
}
const fetchLocation = (callback) => {
const located = () => {
let map, geolocation;
//加载地图,调用浏览器定位服务
map = new AMap.Map('map-container', { // 'map-container' 可以不存在,即不加载地图
resizeEnable: true
});
map.plugin('AMap.Geolocation', function() {
geolocation = new AMap.Geolocation({
enableHighAccuracy: true,//是否使用高精度定位,默认:true
timeout: 10000, //超过10秒后停止定位,默认:无穷大
buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
buttonPosition:'RB'
});
map.addControl(geolocation);
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', (data) => typeof callback === 'function' && callback(transData(data)));//返回定位信息
AMap.event.addListener(geolocation, 'error', (error) => typeof callback === 'function' && callback(null, error)); //返回定位出错信息
});
}
if (!window.AMap) {
if (src) {
inserScript(located);
} else {
console.error('please use setAmapKey to set key');
}
} else if (AMap && !AMap.Map) {
console.error('please use plugin AMap.Geocoder');
} else if (AMap && AMap.Map){
located();
}
}
const inserScript = (cb) => {
const attr = {
name: 'amap_terminus',
src,
type: 'text/javascript'
};
let parent = document.querySelector('body'); // 容器
let script = parent && parent.querySelector(`[name=${attr.name}]`);
if (script) {
if (typeof cb === 'function') {
cb();
}
} else {
script = document.createElement('script');
Object.getOwnPropertyNames(attr).map(name => {
script.setAttribute(name, attr[name]);//暂时只支持一层object
});
parent.appendChild(script).addEventListener('load', () => {
if (typeof cb === 'function') {
cb();
}
}, false);
}
}
const transData = (data) => {
const { addressComponent, formattedAddress, pois, position, POIName, AOIName } = data;
return {
latitude: `${position.lat}`, // 转为string,统一格式
longitude: `${position.lng}`,
formattedAddress,
pois,
province: addressComponent.province,
city: addressComponent.city,
district: addressComponent.district,
citycode: addressComponent.citycode,
adcode: addressComponent.adcode,
street: addressComponent.street,
number: addressComponent.number || addressComponent.streetNumber, // 没有number,存在streetNumber,与rn不一样
country: addressComponent.country, // 没有,与rn不一样
POIName, // 没有,与rn不一样
AOIName, // 没有,与rn不一样
}
}
module.exports.setAmapKey = setAmapKey;
module.exports.fetchLocation = fetchLocation;
import { searchRequestFactory, fetchLocation, mapNavigation } from './app/location';
export const AMapGeocode = searchRequestFactory('geocode')
export const AMapReGeocode = searchRequestFactory('reGeocode')
export const AMapReGeocodeByAmap = searchRequestFactory('reGeocodeByAmap')
export const AMapPOISearch = searchRequestFactory('poiSearch')
export const AMapPOISearchPage = searchRequestFactory('poiSearchWithPage')
export const AMapDistrict = searchRequestFactory('district')
module.exports.fetchLocation = fetchLocation
module.exports.mapNavigation = mapNavigation
export * from './app/amap3d'
import { fetchLocation, setAmapKey } from './app/location';
module.exports.setAmapKey = setAmapKey;
module.exports.fetchLocation = fetchLocation;
//
// Created by Allen Chiang on 17/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface RNAMConfig : NSObject
/**
* 当前app的scheme,用于高德导航唤起以后的回调
*/
@property(nonatomic, copy) NSString *appScheme;
/**
* 高德的appKey
* @param appKey
*/
+ (void)setAppKey:(NSString *)appKey;
+ (instancetype)shareInstance;
@end
\ No newline at end of file
//
// Created by Allen Chiang on 17/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "RNAMConfig.h"
@implementation RNAMConfig
+ (void)setAppKey:(NSString *)appKey {
[AMapServices sharedServices].enableHTTPS = YES;
NSAssert(appKey, @"RNAMConfig.setAppKey appKey can not be nil");
[AMapServices sharedServices].apiKey = appKey;
}
+ (instancetype)shareInstance {
static dispatch_once_t once_t;
static RNAMConfig *shareInstance;
dispatch_once(&once_t, ^{
if (!shareInstance) {
shareInstance = [[RNAMConfig alloc] init];
}
});
return shareInstance;
}
@end
//
// Created by Allen Chiang on 17/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <React/RCTEventEmitter.h>
@interface RNAMGeocodeManager : RCTEventEmitter <RCTBridgeModule>
/**
* 地理编码查询,根据地址信息查询GPS
* @param requestId 请求id
* @param address 详细地址
* @param city 城市名称,中文,英文,或者城市编码均可,非必填项
*/
- (void)requestGeocode:(NSString *)requestId
withAddress:(NSString *)address
withCity:(NSString *)city;
/**
* 逆地理编码查询,根据GPS查询详细地址信息
* @param requestId 请求id
* @param latitude 维度
* @param longitude 经度
*/
- (void)requestReGeocode:(NSString *)requestId
withLatitude:(NSString *)latitude
withLongitude:(NSString *)longitude;
/**
* 检索POI信息
* @param requestId 请求id
* @param keywords POI的搜索关键字
* @param cityCode 城市编码,如果不传会自动获取当前定位所在的citycode
*/
- (void)requestPOISearch:(NSString *)requestId
withKeywords:(NSString *)keywords
withCity:(NSString *)cityCode;
/**
* 获取行政区划数据
* @param requestId 请求id
* @param name 地区名称
*/
- (void)requestDistrictSearch:(NSString *)requestId
name:(nullable NSString *)name;
@end
//
// Created by Allen Chiang on 17/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <AMapSearchKit/AMapSearchKit.h>
#import <React/RCTBridgeModule.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "RNAMGeocodeManager.h"
#import "AMapSearchObject+RNAMRequest.h"
#import "RNAMLocationDO.h"
#import "RNAMResultDO.h"
#import "RNAMPOISearchResultDO.h"
#import "RNAMLocationManager.h"
#import "RNAMDistrictSearchReultDO.h"
static NSString *const kRNAMGeocodeEventNameGeocode = @"geocode";
static NSString *const kRNAMGeocodeEventRequestId = @"requestId";
@interface RNAMGeocodeManager () <AMapSearchDelegate>
@end
@implementation RNAMGeocodeManager {
AMapSearchAPI *_searchAPI;
RNAMLocationManager *_locationManager;
}
@synthesize bridge = _bridge;
- (instancetype)init {
self = [super init];
if (self) {
_searchAPI = [[AMapSearchAPI alloc] init];
[_searchAPI setDelegate:self];
}
return self;
}
- (void)requestGeocode:(NSString *)requestId
withAddress:(NSString *)address
withCity:(NSString *)city {
AMapGeocodeSearchRequest *geo = [[AMapGeocodeSearchRequest alloc] init];
geo.address = address;
geo.city = city;
geo.requestId = requestId;
[_searchAPI AMapGeocodeSearch:geo];
}
- (void)requestReGeocode:(NSString *)requestId
withLatitude:(NSString *)latitude
withLongitude:(NSString *)longitude {
AMapGeoPoint *geoPoint = [[AMapGeoPoint alloc] init];
[geoPoint setLatitude:[latitude floatValue]];
[geoPoint setLongitude:[longitude floatValue]];
AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
[regeo setLocation:geoPoint];
[regeo setRequireExtension:YES];
[regeo setRequestId:requestId];
[_searchAPI AMapReGoecodeSearch:regeo];
}
- (void)requestPOISearch:(NSString *)requestId
withKeywords:(NSString *)keywords
withCity:(NSString *)cityCode {
[self requestPOISearchWithPage:requestId
withKeywords:keywords
withCity:cityCode
withPageNum:0
withPageSize:10];
}
- (void)requestPOISearchWithPage:(NSString *) requestId
withKeywords:(NSString *) keywords
withCity:(NSString *) cityCode
withPageNum:(NSInteger) pageNum
withPageSize:(NSInteger) pageSize{
if (!cityCode || cityCode.length == 0) {
// 没有传入cityCode,需要手动获取一次定位
[self requestPOISearchLiteWithPage:requestId
withKeywords:keywords
withPageNum:pageNum
withPageSize:pageSize];
return;
}
AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
[request setKeywords:keywords];
[request setCityLimit:YES];
[request setRequireSubPOIs:YES];
[request setRequestId:requestId];
[request setPage:pageNum];
[request setCity:cityCode];
[request setOffset:pageSize];
[request setCityLimit:YES];
[request setRequireExtension:YES];
[_searchAPI AMapPOIKeywordsSearch:request];
}
- (void)requestPOISearchLiteWithPage:(NSString *)requestId
withKeywords:(NSString *)keywords
withPageNum:(NSInteger)pageNum
withPageSize:(NSInteger)pageSize {
if(!_locationManager){
_locationManager = [[RNAMLocationManager alloc] init];
}
__weak __typeof(self) weakSelf = self;
[[_locationManager locationManager] requestLocationWithReGeocode:YES
completionBlock:^(CLLocation *location, AMapLocationReGeocode *reGeocode, NSError *error) {
if (error) {
NSLog(@"locError:{%ld - %@};", (long) error.code, error.localizedDescription);
RNAMResultDO *resultDO = [[RNAMResultDO alloc] initWithRequestId:requestId
error:error];
[weakSelf sendEventWithName:kRNAMGeocodeEventNameGeocode
body:[resultDO dictionary]];
return;
}
[weakSelf requestPOISearchWithPage:requestId
withKeywords:keywords
withCity:reGeocode.citycode
withPageNum:pageNum
withPageSize:pageSize];
}];
}
- (void)requestDistrictSearch:(NSString *)requestId
name:(NSString *)name {
AMapDistrictSearchRequest *request = [[AMapDistrictSearchRequest alloc] init];
request.requestId = requestId;
request.keywords = name;
request.requireExtension = YES;
[_searchAPI AMapDistrictSearch:request];
}
#pragma mark - AMapSearchDelegate
- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request
response:(AMapGeocodeSearchResponse *)response {
NSMutableArray *geocodeArray = [[NSMutableArray alloc] init];
[response.geocodes enumerateObjectsUsingBlock:^(AMapGeocode *aMapGeocode, NSUInteger idx, BOOL *stop) {
[geocodeArray addObject:[[[RNAMLocationDO alloc] initWithGeocode:aMapGeocode] dictionary]];
}];
RNAMResultDO *resultDO = [[RNAMResultDO alloc] initWithRequestId:request.requestId
data:@{@"list": geocodeArray}];
[self sendEventWithName:kRNAMGeocodeEventNameGeocode body:[resultDO dictionary]];
}
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request
response:(AMapReGeocodeSearchResponse *)response {
RNAMLocationDO *location = [[RNAMLocationDO alloc] initWithReGeocode:response.regeocode];
RNAMResultDO *resultDO = [[RNAMResultDO alloc] initWithRequestId:request.requestId
locationDO:location];
[self sendEventWithName:kRNAMGeocodeEventNameGeocode
body:[resultDO dictionary]];
}
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request
response:(AMapPOISearchResponse *)response {
RNAMPOISearchResultDO *searchResultDO = [[RNAMPOISearchResultDO alloc] initWithAMapPOISearchResponse:response];
RNAMResultDO *resultDO = [[RNAMResultDO alloc] initWithRequestId:request.requestId data:[searchResultDO dictionary]];
[self sendEventWithName:kRNAMGeocodeEventNameGeocode body:[resultDO dictionary]];
}
- (void)onDistrictSearchDone:(AMapDistrictSearchRequest *)request response:(AMapDistrictSearchResponse *)response {
RNAMDistrictSearchReultDO *district = [[RNAMDistrictSearchReultDO alloc] initWithAMapDistrictSearchResponse:response.districts.firstObject];
RNAMResultDO *resultDO = [[RNAMResultDO alloc] initWithRequestId:request.requestId data:[district dictionary]];
[self sendEventWithName:kRNAMGeocodeEventNameGeocode body:[resultDO dictionary]];
}
- (void)AMapSearchRequest:(id)request
didFailWithError:(NSError *)error {
AMapSearchObject *searchRequest = [request isKindOfClass:[AMapSearchObject class]] ? request : nil;
RNAMResultDO *resultDO = [[RNAMResultDO alloc] initWithRequestId:searchRequest.requestId
error:error];
[self sendEventWithName:kRNAMGeocodeEventNameGeocode
body:[resultDO dictionary] ];
}
- (void)sendReactEvent:(NSString *)requestId withData:(id)data {
RNAMLocationDO *location = nil;
if([data isKindOfClass:[AMapGeocode class]]){
location = [[RNAMLocationDO alloc] initWithGeocode:data];
}
else if([data isKindOfClass:[AMapReGeocode class]]){
location = [[RNAMLocationDO alloc] initWithReGeocode:data];
}
RNAMResultDO *resultDO = [[RNAMResultDO alloc] initWithRequestId:requestId
locationDO:location];
[self sendEventWithName:kRNAMGeocodeEventNameGeocode
body:[resultDO dictionary]];
}
#pragma mark - Export to React Native Method
RCT_EXPORT_MODULE(RNGeocodeManager);
- (NSArray<NSString *> *)supportedEvents {
return @[kRNAMGeocodeEventNameGeocode];
}
- (dispatch_queue_t)methodQueue {
return dispatch_queue_create("io.terminus.react.native.geo.location", DISPATCH_QUEUE_SERIAL);
}
RCT_EXPORT_METHOD(geocode:(NSString *) requestId
withAddress:(NSString *) address
withCity:(NSString *) city) {
[self requestGeocode:requestId withAddress:address withCity:city];
}
RCT_EXPORT_METHOD(reGeocode:(NSString *) requestId
withLatitude:(NSString *) latitude
withLongitude:(NSString *) longitude) {
[self requestReGeocode:requestId
withLatitude:latitude
withLongitude:longitude];
}
RCT_EXPORT_METHOD(poiSearch:(NSString *) requestId
withKeywords:(NSString *) keywords
withCity:(NSString *) cityCode) {
[self requestPOISearch:requestId
withKeywords:keywords
withCity:cityCode];
}
RCT_EXPORT_METHOD(poiSearchWithPage:(NSString*) requestId
withKeywords:(NSString *) keywords
withCity:(NSString *) cityCode
withPageNum:(NSInteger) pageNum
withPageSize:(NSInteger) pageSize){
[self requestPOISearchWithPage:requestId
withKeywords:keywords
withCity:cityCode
withPageNum:pageNum
withPageSize:pageSize];
}
RCT_EXPORT_METHOD(district:(NSString *) requestId
name:(NSString *)name) {
[self requestDistrictSearch:requestId name:name];
}
@end
//
// Created by Allen Chiang on 17/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <React/RCTEventEmitter.h>
@interface RNAMLocationManager : NSObject <RCTBridgeModule>
/**
* 初始化一个AMapLocationManager
* @return AMapLocationManager
*/
- (AMapLocationManager *)locationManager;
/**
* 定位当前位置
*/
- (void)requestLocationResolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject;
@end
//
// Created by Allen Chiang on 17/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <AMapLocationKit/AMapLocationKit.h>
#import "RCTBridgeModule.h"
#import "RNAMLocationManager.h"
#import "RNAMLocationDO.h"
#import "RNAMResultDO.h"
NSString *const kRNAMLocationErrorCode_AuthorizeDeny = @"authorized_deny";
NSString *const kRNAMLocationErrorMessage_AuthorizeDeny = @"请开启定位权限";
@implementation RNAMLocationManager {
AMapLocationManager *_locationManager;
}
@synthesize bridge = _bridge;
- (instancetype)init {
self = [super init];
if (self) {
[self locationManager];
}
return self;
}
- (AMapLocationManager *)locationManager {
if (!_locationManager) {
AMapLocationManager *locationManager = [[AMapLocationManager alloc] init];
[locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
[locationManager setLocationTimeout:2]; // timeout 2 seconds
[locationManager setReGeocodeTimeout:2]; // 逆地理位置 timeout 2 seconds
_locationManager = locationManager;
}
return _locationManager;
}
- (BOOL)hasAuthorized {
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
return (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse
|| status == kCLAuthorizationStatusNotDetermined);
}
- (void)requestLocationResolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject {
// 判断定位权限
if (![self hasAuthorized]) {
reject(kRNAMLocationErrorCode_AuthorizeDeny, kRNAMLocationErrorMessage_AuthorizeDeny,
[NSError errorWithDomain:kRNAMLocationErrorCode_AuthorizeDeny code:0 userInfo:nil]);
return;
}
RCTPromiseResolveBlock resolveCopy = [resolve copy];
RCTPromiseRejectBlock rejectCopy = [reject copy];
[_locationManager requestLocationWithReGeocode:YES
completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
if (error) {
NSLog(@"locError:{%ld - %@};", (long) error.code, error.localizedDescription);
if (rejectCopy) {
rejectCopy([NSString stringWithFormat:@"%d", error.code], error.localizedDescription, error);
}
return;
}
RNAMLocationDO *locationDO = [[RNAMLocationDO alloc] initWithCLLocation:location
withReGeocode:regeocode];
RNAMResultDO *resultDO = [[RNAMResultDO alloc] init];
[resultDO setData:[locationDO dictionary]];
if (resolveCopy) {
resolveCopy([resultDO dictionary]);
}
}];
}
#pragma mark - Export to React Native
RCT_EXPORT_MODULE(RNLocationManager);
RCT_REMAP_METHOD(location,
resolver:
(RCTPromiseResolveBlock) resolve
rejecter:
(RCTPromiseRejectBlock) reject) {
[self requestLocationResolver:resolve rejecter:reject];
}
@end
#import <Foundation/Foundation.h>
#import <React/RCTEventEmitter.h>
@interface RNMapNavigation :NSObject<RCTBridgeModule>
@end
#import "RNAMNavigationManager.h"
#import <MapKit/MapKit.h>
#import "RNAMConfig.h"
@interface RNMapNavigation()
@property(nonatomic,strong) NSString *sname;
@property(nonatomic,strong) NSString *dname;
@property(nonatomic) double slat;
@property(nonatomic) double slon;
@property(nonatomic) double dlat;
@property(nonatomic) double dlon;
@end
@implementation RNMapNavigation
RCT_EXPORT_MODULE(RNMapNavigationManager);
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
RCT_EXPORT_METHOD(mapNavigation:(id)data)
{
if(![data isKindOfClass:[NSDictionary class]]){
return;
}
NSDictionary *params = data;
if([params objectForKey:@"sname"] == nil){
return;
}
if([params objectForKey:@"dname"] == nil){
return;
}
if([params objectForKey:@"slat"] == nil){
return;
}
if([params objectForKey:@"slon"] == nil){
return;
}
if([params objectForKey:@"dlat"] == nil){
return;
}
if([params objectForKey:@"dlon"] == nil){
return;
}
_sname = params[@"sname"];
_dname = params[@"dname"];
_slat = [(NSNumber *) params[@"slat"] doubleValue];
_slon = [(NSNumber *) params[@"slon"] doubleValue];
_dlat = [(NSNumber *) params[@"dlat"] doubleValue];
_dlon = [(NSNumber *) params[@"dlon"] doubleValue];
[self navigationSelect];
}
- (void)navigationSelect {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择导航软件"
message:nil
preferredStyle:UIAlertControllerStyleActionSheet];
[alertController addAction:[UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self navigationAMap];
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"苹果地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self navigationApple];
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
[[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alertController
animated:YES
completion:nil];
}
- (void)navigationApple {
CLLocationCoordinate2D locationCoordinate2D = CLLocationCoordinate2DMake(_dlat, _dlon);
MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:locationCoordinate2D
addressDictionary:nil]];
toLocation.name = _dname;
CLLocationCoordinate2D currentCoordinate2D = CLLocationCoordinate2DMake(_slat,_slon);
MKMapItem *currentLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:currentCoordinate2D postalAddress:nil]];
currentLocation.name = _sname;
[MKMapItem openMapsWithItems:@[currentLocation, toLocation]
launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,
MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
}
- (void)navigationAMap {
NSString *appName = [[NSBundle mainBundle] infoDictionary][@"CFBundleDisplayName"];
NSString *appScheme = [[RNAMConfig shareInstance] appScheme];
NSString *urlString = [NSString stringWithFormat:@"iosamap://path?sourceApplication=%@&sid=BGVIS1&slat=%f&slon=%f&sname=%@&did=BGVIS2&dlat=%f&dlon=%f&dname=%@&dev=0&t=0", appName,_slat,_slon,_sname,_dlat,_dlon,_dname];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url
options:@{}
completionHandler:nil];
} else {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
message:@"请先安装高德APP"
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"确定"
style:UIAlertActionStyleDefault
handler:nil]];
[[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alertController
animated:YES
completion:nil];
return;
}
}
@end
//
// Created by Allen Chiang on 18/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AMapSearchKit/AMapSearchKit.h>
@interface AMapSearchObject (RNAMRequest)
@property(nonatomic, strong) NSString *requestId;
@end
//
// Created by Allen Chiang on 18/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <objc/runtime.h>
#import "AMapSearchObject+RNAMRequest.h"
@implementation AMapSearchObject (RNAMRequest)
- (void)setRequestId:(NSString *)requestId
{
objc_setAssociatedObject(self, @selector(requestId), requestId, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSString *)requestId
{
return objc_getAssociatedObject(self, @selector(requestId));
}
@end
\ No newline at end of file
//
// RNAMDistrictSearchReultDO.h
// Pods
//
// Created by Wenbo Li on 2017/7/11.
//
//
#import <Foundation/Foundation.h>
#import <AMapSearchKit/AMapSearchKit.h>
@interface RNAMDistrictSearchReultDO : NSObject
@property(nonatomic, assign) double latitude;
@property(nonatomic, assign) double longitude;
@property(nonatomic, copy) NSString *adCode;
- (instancetype)initWithAMapDistrictSearchResponse:(AMapDistrict *)district;
- (NSDictionary *)dictionary;
@end
//
// RNAMDistrictSearchReultDO.m
// Pods
//
// Created by Wenbo Li on 2017/7/11.
//
//
#import "RNAMDistrictSearchReultDO.h"
@implementation RNAMDistrictSearchReultDO
- (instancetype)initWithAMapDistrictSearchResponse:(AMapDistrict *)district {
self = [super init];
if (self) {
id adcode = district.adcode;
id center = district.center;
if ([adcode isKindOfClass:[NSString class]]) {
self.adCode = adcode;
}
if ([center isKindOfClass:[AMapGeoPoint class]]) {
self.latitude = [(AMapGeoPoint *)center latitude];
self.longitude = [(AMapGeoPoint *)center longitude];
}
}
return self;
}
- (NSDictionary *)dictionary {
if (self.adCode) {
return @{
@"adCode": self.adCode?self.adCode:@"",
@"latitude": @(self.latitude),
@"longitude": @(self.longitude),
};
}
return @{};
}
@end
//
// Created by Allen Chiang on 17/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
@class CLLocation;
@interface RNAMLocationDO : NSObject
//// gps坐标信息
@property(nonatomic, assign) double latitude;
@property(nonatomic, assign) double longitude;
///格式化地址
@property(nonatomic, copy) NSString *formattedAddress;
///国家
@property(nonatomic, copy) NSString *country;
///省/直辖市
@property(nonatomic, copy) NSString *province;
///市
@property(nonatomic, copy) NSString *city;
///区
@property(nonatomic, copy) NSString *district;
///城市编码
@property(nonatomic, copy) NSString *citycode;
///区域编码
@property(nonatomic, copy) NSString *adcode;
///街道名称
@property(nonatomic, copy) NSString *street;
///门牌号
@property(nonatomic, copy) NSString *number;
///兴趣点名称
@property(nonatomic, copy) NSString *POIName;
///所属兴趣点名称
@property(nonatomic, copy) NSString *AOIName;
// poi列表
@property(nonatomic, copy) NSArray *pois;
@property(nonatomic, copy) NSArray *aois;
- (id)initWithCLLocation:(CLLocation *)location
withReGeocode:(AMapLocationReGeocode *)reGeocode;
- (id)initWithGeocode:(AMapGeocode *)mapGeocode;
- (id)initWithReGeocode:(AMapReGeocode *)mapReGeocode;
- (NSDictionary *)dictionary;
@end
//
// Created by Allen Chiang on 17/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "RNAMLocationDO.h"
#import "RNAMPOISearchResultDO.h"
@implementation RNAMLocationDO
- (instancetype)initWithCLLocation:(CLLocation *)location
withReGeocode:(AMapLocationReGeocode *)reGeocode {
self = [super init];
if (self) {
_latitude = location.coordinate.latitude;
_longitude = location.coordinate.longitude;
if (reGeocode) {
_formattedAddress = reGeocode.formattedAddress;
_country = reGeocode.country;
_province = reGeocode.province;
_city = reGeocode.city;
_district = reGeocode.district;
_citycode = reGeocode.citycode;
_adcode = reGeocode.adcode;
_street = reGeocode.street;
_number = reGeocode.number;
_POIName = reGeocode.POIName;
_AOIName = reGeocode.AOIName;
}
}
return self;
}
- (id)initWithGeocode:(AMapGeocode *)mapGeocode {
self = [super init];
if(self){
_formattedAddress = mapGeocode.formattedAddress;
_country = mapGeocode.township;
_province = mapGeocode.province;
_city = mapGeocode.city;
_district = mapGeocode.district;
_citycode = mapGeocode.citycode;
_adcode = mapGeocode.adcode;
_latitude = mapGeocode.location.latitude;
_longitude = mapGeocode.location.longitude;
}
return self;
}
- (id)initWithReGeocode:(AMapReGeocode *)mapReGeocode {
self = [super init];
if (self) {
_formattedAddress = mapReGeocode.formattedAddress;
AMapAddressComponent *addressComponent = mapReGeocode.addressComponent;
AMapStreetNumber *streetNumber = addressComponent.streetNumber;
_country = addressComponent.township;
_province = addressComponent.province;
_citycode = addressComponent.citycode;
_city = addressComponent.city;
_district = addressComponent.district;
_adcode = addressComponent.adcode;
_street = streetNumber.street;
_number = streetNumber.number;
_latitude = streetNumber.location.latitude;
_longitude = streetNumber.location.longitude;
if(mapReGeocode.pois){
NSMutableArray *pois = [[NSMutableArray alloc] init];
[mapReGeocode.pois enumerateObjectsUsingBlock:^(AMapPOI * _Nonnull aMapPOI, NSUInteger idx, BOOL * _Nonnull stop) {
if(aMapPOI.adcode){
aMapPOI.adcode = addressComponent.adcode;
}
RNAMPOI *poiDO = [[RNAMPOI alloc] initWithAMapPOI:aMapPOI];
[pois addObject:[poiDO dictionary]];
}];
_pois = pois;
}
if(mapReGeocode.aois){
NSMutableArray *aois = [[NSMutableArray alloc] init];
[mapReGeocode.aois enumerateObjectsUsingBlock:^(AMapAOI * _Nonnull aMapPOI, NSUInteger idx, BOOL * _Nonnull stop) {
[aois addObject: [aMapPOI name]];
}];
_aois = aois;
}
}
return self;
}
- (NSDictionary *)dictionary {
return @{
@"latitude": [NSString stringWithFormat:@"%f", _latitude],
@"longitude": [NSString stringWithFormat:@"%f", _longitude],
@"formattedAddress": _formattedAddress?:@"",
@"country": _country?:@"",
@"province": _province?:@"",
@"city": _city?:@"",
@"district": _district?:@"",
@"cityCode": _citycode?:@"",
@"adCode": _adcode?:@"",
@"street": _street?:@"",
@"number": _number?:@"",
@"POIName": _POIName?:@"",
@"AOIName": _AOIName?:@"",
@"pois": _pois?:@{},
@"aois": _aois?:@{}
};
}
@end
//
// Created by Allen Chiang on 18/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AMapSearchKit/AMapSearchKit.h>
@interface RNAMPOI : NSObject
- (instancetype)initWithAMapPOI:(AMapPOI *)aMapPOI;
- (NSDictionary *)dictionary;
@end
@interface RNAMPOISuggestion : NSObject
- (instancetype)initWithAMapSuggestion:(AMapSuggestion *)suggestion;
- (NSDictionary *)dictionary;
@end
@interface RNAMPOISearchResultDO : NSObject
@property(nonatomic, copy) NSArray *pois;
@property(nonatomic, assign) NSInteger count;
@property(nonatomic, copy) RNAMPOISuggestion *suggestions;
- (instancetype)initWithAMapPOISearchResponse:(AMapPOISearchResponse *)searchResponse;
- (NSDictionary *)dictionary;
@end
\ No newline at end of file
//
// Created by Allen Chiang on 18/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <AMapSearchKit/AMapSearchKit.h>
#import "RNAMPOISearchResultDO.h"
@implementation RNAMPOI {
AMapPOI *_aMapPOI;
}
- (instancetype)initWithAMapPOI:(AMapPOI *)aMapPOI {
self = [super init];
if (self) {
_aMapPOI = [aMapPOI copy];
}
return self;
}
- (NSDictionary *)dictionary {
if (_aMapPOI) {
return @{
@"uid": _aMapPOI.uid ?: @"",
@"name": _aMapPOI.name ?: @"",
@"type": _aMapPOI.type ?: @"",
@"address": _aMapPOI.address ?: @"",
@"adcode": _aMapPOI.adcode ?: @"",
@"latitude": _aMapPOI.location.latitude?[NSString stringWithFormat:@"%f",_aMapPOI.location.latitude]:@"",
@"longitude": _aMapPOI.location.longitude?[NSString stringWithFormat:@"%f",_aMapPOI.location.longitude]:@""
};
}
return @{};
}
@end
@implementation RNAMPOISuggestion {
AMapSuggestion *_suggestion;
}
- (instancetype)initWithAMapSuggestion:(AMapSuggestion *)suggestion {
self = [super init];
if (self) {
_suggestion = [suggestion copy];
}
return self;
}
- (NSDictionary *)dictionary {
if (_suggestion) {
return @{
@"keywords": _suggestion.keywords ?: @[]
};
}
return @{};
}
@end
@implementation RNAMPOISearchResultDO
- (instancetype)initWithAMapPOISearchResponse:(AMapPOISearchResponse *)searchResponse {
self = [super init];
if (self) {
_count = searchResponse.count;
NSMutableArray *pois = [[NSMutableArray alloc] init];
[searchResponse.pois enumerateObjectsUsingBlock:^(AMapPOI *aMapPOI, NSUInteger idx, BOOL *stop) {
[pois addObject:[[[RNAMPOI alloc] initWithAMapPOI:aMapPOI] dictionary]];
}];
_pois = pois;
_suggestions = [[RNAMPOISuggestion alloc] initWithAMapSuggestion:searchResponse.suggestion];
}
return self;
}
- (NSDictionary *)dictionary {
return @{
@"count": @(_count),
@"pois": _pois ?: @[],
@"suggestions": [_suggestions dictionary] ?: @{}
};
}
@end
//
// Created by Allen Chiang on 18/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "RNAMLocationDO.h"
@interface RNAMResultErrorDO : NSObject
@property(nonatomic, copy) NSString *domain;
@property(nonatomic, assign) NSInteger code;
@property(nonatomic, copy) NSDictionary *userInfo;
- (instancetype)initWithError:(NSError *)error;
- (NSDictionary *)dictionary;
@end
@interface RNAMResultDO : NSObject
@property(nonatomic, copy) NSString *requestId;
@property(nonatomic, copy) NSDictionary *data;
@property(nonatomic, copy) RNAMResultErrorDO *error;
- (instancetype)initWithRequestId:(NSString *)requestId
data:(NSDictionary *)data;
- (instancetype)initWithRequestId:(NSString *)requestId
locationDO:(RNAMLocationDO *)locationDO;
- (instancetype)initWithRequestId:(NSString *)requestId
error:(NSError *)error;
- (NSDictionary *)dictionary;
@end
\ No newline at end of file
//
// Created by Allen Chiang on 18/01/2017.
// Copyright (c) 2017 Facebook. All rights reserved.
//
#import "RNAMResultDO.h"
#import "RNAMLocationDO.h"
@implementation RNAMResultErrorDO
- (instancetype)initWithError:(NSError *)error {
self = [super init];
if (self) {
_domain = error.domain;
_code = error.code;
_userInfo = error.userInfo;
}
return self;
}
- (NSDictionary *)dictionary {
return @{
@"domain": _domain ?: @"",
@"code": @(_code),
@"userInfo": _userInfo ?: @{}
};
}
@end
@implementation RNAMResultDO
- (instancetype)initWithRequestId:(NSString *)requestId
data:(NSDictionary *)data {
self = [super init];
if (self) {
_requestId = requestId;
_data = data;
}
return self;
}
- (instancetype)initWithRequestId:(NSString *)requestId
locationDO:(RNAMLocationDO *)locationDO {
return [self initWithRequestId:requestId data:[locationDO dictionary]];
}
- (instancetype)initWithRequestId:(NSString *)requestId
error:(NSError *)error {
self = [super init];
if (self) {
_requestId = requestId;
_error = [[RNAMResultErrorDO alloc] initWithError:error];
}
return self;
}
- (NSDictionary *)dictionary {
if (_error) {
return @{
@"requestId": _requestId ?: @"",
@"error": _error ? [_error dictionary] : @{}
};
}
return @{
@"requestId": _requestId ?: @"",
@"data": _data ?: @{}
};
}
@end
\ No newline at end of file
//
// Created by Allen Chiang on 16/3/17.
// Copyright (c) 2016 terminus. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSObject (RNAIU_ToDictionary)
- (NSDictionary *)RNAIU_ToDictionary;
- (NSDictionary *)RNAIU_ToDictionaryWithDepth:(NSInteger)depth;
@end
//
// Created by Allen Chiang on 16/3/17.
// Copyright (c) 2016 terminus. All rights reserved.
//
#import <objc/runtime.h>
#import <objc/message.h>
#import "NSObject+RNAIU_ToDictionary.h"
#import "RNAIUConvertDefine.h"
@implementation NSObject (RNAIU_ToDictionary)
- (NSDictionary *)RNAIU_ToDictionary {
if ([self isKindOfClass:[NSDictionary class]]) {
return (NSDictionary *)self;
}
return [self toDictionaryOrArrayWithDepth:8];
}
- (NSDictionary *)RNAIU_ToDictionaryWithDepth:(NSInteger)depth{
return [self toDictionaryOrArrayWithDepth:depth];
}
- (id)toDictionaryOrArrayWithDepth:(NSUInteger)depth {
if ([self isKindOfClass:[NSArray class]] || [self isKindOfClass:[NSSet class]]) {
id selfObj = self;
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:[selfObj count]];
if (depth > 0) {
for (id o in selfObj) {
[array addObject:[o toDictionaryOrArrayWithDepth:depth - 1]];
}
}
return array;
} else if ([self isKindOfClass:[NSDictionary class]]) {
NSDictionary *selfObj = (NSDictionary *) self;
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:[selfObj count]];
if (depth > 0) {
[selfObj enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[dic setObject:[obj toDictionaryOrArrayWithDepth:depth - 1]
forKey:key];
}];
}
return dic;
} else if ([self isKindOfClass:[NSNull class]] || [self isKindOfClass:[NSNumber class]]
|| [self isKindOfClass:[NSString class]]) {
return self;
} else if (self == nil) {
return [NSNull null];
} else {
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:10];
Class clazz = [self class];
[RNAPropertyAttributeInfo enumerateClassProperties:clazz
withInfoBlock:^(Class oriClass, Class currentClass, RNAPropertyAttributeInfo *info) {
[self getPropertyToDictionary:dic
pProperty:info
withDepth:depth
withClass:clazz];
}];
return dic;
}
}
- (void)getPropertyToDictionary:(NSMutableDictionary *)dictionary
pProperty:(RNAPropertyAttributeInfo *)attributeInfo
withDepth:(NSUInteger)depth
withClass:(Class)clazz {
if (attributeInfo.transient) {
//不需要对这个字段进行序列化
return;
}
SEL getter = attributeInfo.getter;
id retForId = nil;
char retForChar;
unsigned char retForUnsignedChar;
bool retForBool;
double retForDouble;
int retForInt;
float retForFloat;
long retForLong;
unsigned long retForUnsignedLong;
long long retForLongLong;
unsigned long long retForUnsignedLongLong;
short retForShort;
unsigned short retForUnsignedShort;
unsigned retForUnsigned;
switch (attributeInfo.type) {
case RNAIU_CHAR:
retForChar = ((char ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithChar:retForChar]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_UNSIGNED_CHAR:
retForUnsignedChar = ((unsigned char ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithUnsignedChar:retForUnsignedChar]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_C_BOOL:
retForBool = ((bool ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithBool:retForBool]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_DOUBLE:
retForDouble = ((double ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithDouble:retForDouble]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_INT:
retForInt = ((int ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithInt:retForInt]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_FLOAT:
retForFloat = ((float ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithFloat:retForFloat]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_LONG:
retForLong = ((long ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithLong:retForLong]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_UNSIGNED_LONG:
retForUnsignedLong = ((unsigned long ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithUnsignedLong:retForUnsignedLong]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_LONG_LONG:
retForLongLong = ((long long ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithLongLong:retForLongLong]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_UNSIGNED_LONG_LONG:
retForUnsignedLongLong = ((unsigned long long ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithUnsignedLongLong:retForUnsignedLongLong]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_SHORT:
retForShort = ((short ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithShort:retForShort]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_UNSIGNED_SHORT:
retForUnsignedShort = ((unsigned short ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithUnsignedShort:retForUnsignedShort]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_UNSIGNED:
retForUnsigned = ((unsigned ( *)(id, SEL)) objc_msgSend)(self, getter);
[dictionary setObject:[NSNumber numberWithUnsignedInt:retForUnsigned]
forKey:attributeInfo.dicPropertyName];
return;
case RNAIU_ID:
retForId = ((id ( *)(id, SEL)) objc_msgSend)(self, getter);
if (retForId) {
if ([retForId isKindOfClass:[NSString class]] || [retForId isKindOfClass:[NSNumber class]]) {
[dictionary setObject:retForId
forKey:attributeInfo.dicPropertyName];
} else {
if (depth == 0) {
return;
}
[dictionary setObject:[retForId toDictionaryOrArrayWithDepth:depth - 1]
forKey:attributeInfo
.dicPropertyName];
}
}
return;
default:
break;
}
}
@end
//
// Created by Allen Chiang on 16/2/18.
// Copyright (c) 2016 terminus. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
typedef enum {
RNAIU_CHAR, RNAIU_UNSIGNED_CHAR, RNAIU_SHORT, RNAIU_UNSIGNED_SHORT, RNAIU_INT, RNAIU_UNSIGNED, RNAIU_LONG, RNAIU_UNSIGNED_LONG,
RNAIU_LONG_LONG, RNAIU_UNSIGNED_LONG_LONG, RNAIU_DOUBLE, RNAIU_FLOAT, RNAIU_C_BOOL,
RNAIU_ID, RNAIU_STRUCT, RNAIU_FUNC, RNAIU_BLOCK, RNAIU_INT_P, RNAIU_VOID_P, RNAIU_CHAR_P, RNAIU_NIL
} RNAIU_TypeOfProperty;
@protocol RNAIUTransient
@end
@interface RNAPropertyAttributeInfo : NSObject
@property BOOL transient;
@property BOOL readOnly;
@property RNAIU_TypeOfProperty type;
@property Class clazz;
@property Class arrayClass;
@property(nonatomic, copy) NSString *dicPropertyName;
@property(nonatomic, copy) NSString *oriPropertyName;
@property SEL getter;
@property SEL setter;
@property(nonatomic, strong) NSArray *protocols;
+ (RNAPropertyAttributeInfo *)analyseProperty:(objc_property_t)pProperty
WithClass:(Class)aClass
AndWithCurrentClass:(Class)currentClass;
+ (void)enumerateClassProperties:(Class)aClass
withInfoBlock:(void (^)(Class oriClass, Class currentClass, RNAPropertyAttributeInfo *info))infoBlock;
+ (id)getValue:(id)obj with:(RNAPropertyAttributeInfo *)info;
+ (NSArray *)getProtocolsFromClass:(Class)clazz;
@end
@interface RNAPropertyAttributeInfoCache : NSObject
+ (RNAPropertyAttributeInfoCache *)instance;
- (RNAPropertyAttributeInfo *)getFromCacheWithClass:(Class)clazz AndPropertyName:(NSString *)name;
- (void)putToCacheWithClass:(Class)clazz AndPropertyName:(NSString *)name WithInfo:(RNAPropertyAttributeInfo *)info;
@end
@interface RNAIUConvertDefine :NSObject
@end
//
// Created by Allen Chiang on 16/2/18.
// Copyright (c) 2016 terminus. All rights reserved.
//
#import <objc/message.h>
#import "RNAIUConvertDefine.h"
#import <libextobjc/extobjc.h>
@implementation RNAPropertyAttributeInfoCache {
@private
NSCache *_cache;
}
- (id)init {
self = [super init];
if (self) {
_cache = [[NSCache alloc] init];
}
return self;
}
- (void)dealloc {
#if TARGET_OS_IPHONE
[[NSNotificationCenter defaultCenter] removeObserver:self];
#endif
}
+ (RNAPropertyAttributeInfoCache *)instance {
static RNAPropertyAttributeInfoCache *_instance = nil;
static dispatch_once_t _oncePredicate_PropertyAttributeInfoCache;
dispatch_once(&_oncePredicate_PropertyAttributeInfoCache, ^{
if (_instance == nil) {
_instance = [[self alloc] init];
}
}
);
return _instance;
}
- (RNAPropertyAttributeInfo *)getFromCacheWithClass:(Class)clazz
AndPropertyName:(NSString *)name {
@synchronized (self) {
NSDictionary *proInfos = [_cache objectForKey:NSStringFromClass(clazz)];
if (proInfos) {
RNAPropertyAttributeInfo *info = [proInfos objectForKey:name];
return info;
}
return nil;
}
}
- (void)putToCacheWithClass:(Class)clazz AndPropertyName:(NSString *)name
WithInfo:(RNAPropertyAttributeInfo *)info {
@synchronized (self) {
NSMutableDictionary *proInfos = [_cache objectForKey:NSStringFromClass(clazz)];
if (proInfos == nil) {
proInfos = [[NSMutableDictionary alloc] initWithCapacity:1];
[_cache setObject:proInfos
forKey:NSStringFromClass(clazz)];
}
[proInfos setObject:info
forKey:name];
}
}
- (void)clearCache {
@synchronized (self) {
[_cache removeAllObjects];
}
}
@end
@implementation RNAPropertyAttributeInfo {
@private
BOOL _transient;
BOOL _readOnly;
RNAIU_TypeOfProperty _type;
Class _clazz;
Class _arrayClass;
NSString *_dicPropertyName;
NSString *_oriPropertyName;
SEL _getter;
SEL _setter;
NSArray *_protocols;
}
@synthesize transient = _transient;
@synthesize readOnly = _readOnly;
@synthesize type = _type;
@synthesize clazz = _clazz;
@synthesize arrayClass = _arrayClass;
@synthesize dicPropertyName = _dicPropertyName;
@synthesize oriPropertyName = _oriPropertyName;
@synthesize getter = _getter;
@synthesize setter = _setter;
@synthesize protocols = _protocols;
+ (RNAPropertyAttributeInfo *)analyseProperty:(objc_property_t)pProperty
WithClass:(Class)aClass
AndWithCurrentClass:(Class)currentClass {
NSMutableString *propertyName = [NSMutableString stringWithUTF8String:property_getName(pProperty)];
RNAPropertyAttributeInfo *info;
if ((info = [[RNAPropertyAttributeInfoCache instance] getFromCacheWithClass:aClass
AndPropertyName:propertyName]) != nil) {
return info;
}
ext_propertyAttributes* pAttributes = ext_copyPropertyAttributes(pProperty);
if (NULL == pAttributes) {
return nil;
}
RNAIU_TypeOfProperty typeOfProperty = RNAIU_NIL;
Class clazz = nil;
BOOL transient = NO;
BOOL readOnly = pAttributes->readonly;
Class arrayClass = nil;
NSMutableArray *protocols = [[NSMutableArray alloc] initWithCapacity:2];
NSString *dicPropertyName = propertyName;
NSString *typeAtt = [NSString stringWithCString:pAttributes->type
encoding:NSUTF8StringEncoding];
if ([typeAtt hasPrefix:@"c"]) {
typeOfProperty = RNAIU_CHAR;
} else if ([typeAtt hasPrefix:@"C"]) {
typeOfProperty = RNAIU_UNSIGNED_CHAR;
} else if ([typeAtt hasPrefix:@"B"]) {
typeOfProperty = RNAIU_C_BOOL;
} else if ([typeAtt hasPrefix:@"d"]) {
typeOfProperty = RNAIU_DOUBLE;
} else if ([typeAtt hasPrefix:@"i"]) {
typeOfProperty = RNAIU_INT;
} else if ([typeAtt hasPrefix:@"f"]) {
typeOfProperty = RNAIU_FLOAT;
} else if ([typeAtt hasPrefix:@"l"]) {
typeOfProperty = RNAIU_LONG;
} else if ([typeAtt hasPrefix:@"L"]) {
typeOfProperty = RNAIU_UNSIGNED_LONG;
} else if ([typeAtt hasPrefix:@"q"]) {
typeOfProperty = RNAIU_LONG_LONG;
} else if ([typeAtt hasPrefix:@"Q"]) {
typeOfProperty = RNAIU_UNSIGNED_LONG_LONG;
} else if ([typeAtt hasPrefix:@"s"]) {
typeOfProperty = RNAIU_SHORT;
} else if ([typeAtt hasPrefix:@"S"]) {
typeOfProperty = RNAIU_UNSIGNED_SHORT;
} else if ([typeAtt hasPrefix:@"{"]) {
typeOfProperty = RNAIU_STRUCT;
} else if ([typeAtt hasPrefix:@"I"]) {
typeOfProperty = RNAIU_UNSIGNED;
} else if ([typeAtt hasPrefix:@"^i"]) {
typeOfProperty = RNAIU_INT_P;
} else if ([typeAtt hasPrefix:@"^v"]) {
typeOfProperty = RNAIU_VOID_P;
} else if ([typeAtt hasPrefix:@"^?"]) {
typeOfProperty = RNAIU_FUNC;
} else if ([typeAtt hasPrefix:@"*"]) {
typeOfProperty = RNAIU_CHAR_P;
} else if ([typeAtt hasPrefix:@"@"]) {
if ([typeAtt hasSuffix:[NSString stringWithCString:@encode(void (^)())
encoding:NSUTF8StringEncoding]]) {
typeOfProperty = RNAIU_BLOCK;
} else {
typeOfProperty = RNAIU_ID;
clazz = pAttributes->objectClass;
NSString *propertyType = nil;
NSString *arrayClassName;
NSString *attrStrForScan = typeAtt;
const char *const attrString = property_getAttributes(pProperty);
if (attrString) { //兼容iOS5 原来在iOS5 上NSGetSizeAndAlignment有bug 导致取出的typeAtt不对
attrStrForScan = @(attrString + 1);
}
NSScanner *scanner = [NSScanner scannerWithString:attrStrForScan];
if ([scanner scanString:@"@\""
intoString:&propertyType]) {
[scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@"\"<"]
intoString:&propertyType];
if (!clazz) {
clazz = NSClassFromString(propertyType);
}
while ([scanner scanString:@"<"
intoString:NULL]) {
NSString *protocolName = nil;
[scanner scanUpToString:@">"
intoString:&protocolName];
if (protocolName) {
[protocols addObject:protocolName];
}
if ([protocolName isEqualToString:NSStringFromProtocol(@protocol(RNAIUTransient))]) {
transient = YES;
} else {
arrayClassName = protocolName;
}
[scanner scanString:@">"
intoString:NULL];
}
}
if ([clazz isSubclassOfClass:[NSArray class]] || [clazz isSubclassOfClass:[NSSet class]]) {
if (arrayClassName) {
arrayClass = NSClassFromString(arrayClassName);
}
}
}
}
info = [[RNAPropertyAttributeInfo alloc] init];
info.readOnly = readOnly;
info.clazz = clazz;
info.type = typeOfProperty;
info.arrayClass = arrayClass;
info.dicPropertyName = dicPropertyName;
info.oriPropertyName = propertyName;
info.transient = [propertyName hasPrefix:@"_"] || transient;
info.setter = pAttributes->setter;
info.getter = pAttributes->getter;
info.protocols = protocols;
[[RNAPropertyAttributeInfoCache instance]
putToCacheWithClass:aClass
AndPropertyName:propertyName
WithInfo:info];
if (pAttributes != NULL) {
free(pAttributes);
}
return info;
}
+ (void)enumerateClassProperties:(Class)aClass
withInfoBlock:(void (^)(Class oriClass, Class currentClass, RNAPropertyAttributeInfo *info))infoBlock {
if (!infoBlock) {
return;
}
Class clazz = aClass;
while (clazz != nil) {
if (clazz == [NSObject class]) {
break;
}
unsigned int propertyCount;
objc_property_t *pProperty = class_copyPropertyList(clazz, &propertyCount);
if (pProperty && propertyCount > 0) {
for (unsigned int i = 0; i < propertyCount; i++) {
RNAPropertyAttributeInfo *info = [RNAPropertyAttributeInfo analyseProperty:pProperty[i]
WithClass:aClass
AndWithCurrentClass:clazz];
if (![info.oriPropertyName hasSuffix:@"ext_annotation_marker"]) {
if (class_conformsToProtocol(clazz, @protocol(NSObject)) &&
([@"hash" isEqualToString:info.oriPropertyName] ||
[@"superclass" isEqualToString:info.oriPropertyName] ||
[@"description" isEqualToString:info.oriPropertyName] ||
[@"debugDescription" isEqualToString:info.oriPropertyName])) {
continue;
}
infoBlock(aClass, clazz, info);
}
}
}
if (pProperty) {
free(pProperty);
}
clazz = class_getSuperclass(clazz);
}
}
+ (id)getValue:(id)obj with:(RNAPropertyAttributeInfo *)attributeInfo {
SEL getter = attributeInfo.getter;
id retForId = nil;
char retForChar;
unsigned char retForUnsignedChar;
bool retForBool;
double retForDouble;
int retForInt;
float retForFloat;
long retForLong;
unsigned long retForUnsignedLong;
long long retForLongLong;
unsigned long long retForUnsignedLongLong;
short retForShort;
unsigned short retForUnsignedShort;
unsigned retForUnsigned;
switch (attributeInfo.type) {
case RNAIU_CHAR:
retForChar = ((char (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithChar:retForChar];
case RNAIU_UNSIGNED_CHAR:
retForUnsignedChar = ((unsigned char (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithUnsignedChar:retForUnsignedChar];
case RNAIU_C_BOOL:
retForBool = ((bool (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithBool:retForBool];
case RNAIU_DOUBLE:
retForDouble = ((double (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithDouble:retForDouble];
case RNAIU_INT:
retForInt = ((int (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithInt:retForInt];
case RNAIU_FLOAT:
retForFloat = ((float (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithFloat:retForFloat];
case RNAIU_LONG:
retForLong = ((long (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithLong:retForLong];
case RNAIU_UNSIGNED_LONG:
retForUnsignedLong = ((unsigned long (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithUnsignedLong:retForUnsignedLong];
case RNAIU_LONG_LONG:
retForLongLong = ((long long (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithLongLong:retForLongLong];
case RNAIU_UNSIGNED_LONG_LONG:
retForUnsignedLongLong = ((unsigned long long (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithUnsignedLongLong:retForUnsignedLongLong];
case RNAIU_SHORT:
retForShort = ((short (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithShort:retForShort];
case RNAIU_UNSIGNED_SHORT:
retForUnsignedShort = ((unsigned short (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithUnsignedShort:retForUnsignedShort];
case RNAIU_UNSIGNED:
retForUnsigned = ((unsigned (*)(id, SEL)) objc_msgSend)(obj, getter);
return [NSNumber numberWithUnsignedInt:retForUnsigned];
case RNAIU_ID:
retForId = ((id (*)(id, SEL)) objc_msgSend)(obj, getter);
return retForId;
default:
break;
}
return nil;
}
+ (NSArray *)getProtocolsFromClass:(Class)clazz {
unsigned int propertyCount;
Protocol *__unsafe_unretained *pProtocol = class_copyProtocolList(clazz, &propertyCount);
NSMutableArray *result = [[NSMutableArray alloc] initWithCapacity:propertyCount];
if (pProtocol && propertyCount > 0) {
for (unsigned int i = 0; i < propertyCount; i++) {
[result addObject:NSStringFromProtocol(pProtocol[i])];
}
}
if (pProtocol) {
free(pProtocol);
}
return result;
}
@end
@implementation RNAIUConvertDefine
@end
#import <MAMapKit/MAMapKit.h>
@interface Coordinate : NSObject
@property(nonatomic, assign) CLLocationCoordinate2D coordinate;
- (instancetype)initWithCoordinate:(CLLocationCoordinate2D)coordinate;
@end
\ No newline at end of file
#import "Coordinate.h"
@implementation Coordinate {
}
- (instancetype)initWithCoordinate:(CLLocationCoordinate2D)coordinate {
self = [super init];
self.coordinate = coordinate;
return self;
}
@end
\ No newline at end of file
#import <MAMapKit/MAMapKit.h>
@interface LocationStyle : NSObject
@property(nonatomic, strong) UIImage *image;
@property(nonatomic, strong) UIColor *fillColor;
@property(nonatomic, strong) UIColor *strokeColor;
@property(nonatomic, assign) CGFloat strokeWidth;
@end
\ No newline at end of file
#import "LocationStyle.h"
@implementation LocationStyle
@end
\ No newline at end of file
#import <MAMapKit/MAMapView.h>
#import <React/RCTConvert.h>
#import <React/RCTConvert+CoreLocation.h>
#import "Coordinate.h"
#import "LocationStyle.h"
@implementation RCTConvert (AMapView)
RCT_ENUM_CONVERTER(MAMapType, (@{
@"standard": @(MAMapTypeStandard),
@"satellite": @(MAMapTypeSatellite),
}), MAMapTypeStandard, integerValue)
RCT_ENUM_CONVERTER(MAPinAnnotationColor, (@{
@"red": @(MAPinAnnotationColorRed),
@"green": @(MAPinAnnotationColorGreen),
@"purple": @(MAPinAnnotationColorPurple),
}), MAPinAnnotationColorRed, integerValue)
+ (Coordinate *)Coordinate:(id)json {
return [[Coordinate alloc] initWithCoordinate:[self CLLocationCoordinate2D:json]];
}
+ (LocationStyle *)LocationStyle:(id)json {
LocationStyle *locationStyle = [LocationStyle new];
locationStyle.fillColor = [self UIColor:json[@"fillColor"]];
locationStyle.strokeColor = [self UIColor:json[@"strokeColor"]];
locationStyle.strokeWidth = [self CGFloat:json[@"strokeWidth"]];
locationStyle.image = [UIImage imageNamed:[self NSString:json[@"image"]]];
return locationStyle;
}
+ (MAHeatMapNode *)MAHeatMapNode:(id)json {
MAHeatMapNode *node = [MAHeatMapNode new];
node.coordinate = [self CLLocationCoordinate2D:json];
node.intensity = 1;
return node;
}
+ (MACoordinateRegion)MACoordinateRegion:(id)json {
return MACoordinateRegionMake(
[self CLLocationCoordinate2D:json],
MACoordinateSpanMake(
[self CLLocationDegrees:json[@"latitudeDelta"]],
[self CLLocationDegrees:json[@"longitudeDelta"]]));
}
RCT_ARRAY_CONVERTER(Coordinate)
RCT_ARRAY_CONVERTER(MAHeatMapNode)
@end
#import <React/RCTView.h>
@interface AMapCallout : RCTView
@end
#import "AMapCallout.h"
@implementation AMapCallout
@end
#import <React/RCTUIManager.h>
#import "AMapCallout.h"
#pragma ide diagnostic ignored "OCUnusedClassInspection"
@interface AMapCalloutManager : RCTViewManager
@end
@implementation AMapCalloutManager {
}
RCT_EXPORT_MODULE(AMapInfoWindow)
- (UIView *)view {
return [AMapCallout new];
}
@end
#import <MAMapKit/MAMapKit.h>
#import "AMapOverlay.h"
#pragma ide diagnostic ignored "OCUnusedPropertyInspection"
@interface AMapCircle : AMapOverlay
@property(nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property(nonatomic, readonly) MAMapRect boundingMapRect;
@end
#import "AMapCircle.h"
#pragma ide diagnostic ignored "OCUnusedMethodInspection"
@implementation AMapCircle {
MACircle *_circle;
MACircleRenderer *_renderer;
CGFloat _strokeWidth;
UIColor *_strokeColor;
UIColor *_fillColor;
CLLocationCoordinate2D _coordinate;
CLLocationDistance _radius;
}
- (void)setCoordinate:(CLLocationCoordinate2D)coordinate {
_coordinate = coordinate;
_circle.coordinate = coordinate;
}
- (void)setStrokeWidth:(CGFloat)strokeWidth {
_strokeWidth = strokeWidth;
_renderer.lineWidth = strokeWidth;
}
- (void)setStrokeColor:(UIColor *)strokeColor {
_strokeColor = strokeColor;
_renderer.strokeColor = strokeColor;
}
- (void)setFillColor:(UIColor *)fillColor {
_fillColor = fillColor;
_renderer.fillColor = fillColor;
}
- (CLLocationCoordinate2D)coordinate {
return _circle.coordinate;
}
- (MAMapRect)boundingMapRect {
return _circle.boundingMapRect;
}
- (void)setRadius:(CLLocationDistance)radius {
_radius = radius;
}
- (MAOverlayRenderer *)renderer {
if (_strokeColor == nil) {
_strokeColor = UIColor.blackColor;
}
if (_renderer == nil) {
_circle = [MACircle circleWithCenterCoordinate:_coordinate radius:_radius];
_renderer = [[MACircleRenderer alloc] initWithCircle:_circle];
_renderer.lineWidth = _strokeWidth;
_renderer.strokeColor = _strokeColor;
_renderer.fillColor = _fillColor;
}
return _renderer;
}
@end
#import <MAMapKit/MAMapView.h>
#import <React/RCTViewManager.h>
#import "AMapCircle.h"
#pragma ide diagnostic ignored "OCUnusedClassInspection"
@interface AMapCircleManager : RCTViewManager
@end
@implementation AMapCircleManager {
}
RCT_EXPORT_MODULE()
- (UIView *)view {
return [AMapCircle new];
}
RCT_EXPORT_VIEW_PROPERTY(coordinate, CLLocationCoordinate2D)
RCT_EXPORT_VIEW_PROPERTY(radius, CLLocationDistance)
RCT_EXPORT_VIEW_PROPERTY(strokeWidth, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(strokeColor, UIColor)
RCT_EXPORT_VIEW_PROPERTY(fillColor, UIColor)
@end
#import "AMapView.h"
#import "AMapCallout.h"
@interface AMapMarker : UIView
@property(nonatomic, copy) RCTBubblingEventBlock onPress;
@property(nonatomic, copy) RCTBubblingEventBlock onInfoWindowPress;
@property(nonatomic, copy) RCTBubblingEventBlock onDragStart;
@property(nonatomic, copy) RCTBubblingEventBlock onDrag;
@property(nonatomic, copy) RCTBubblingEventBlock onDragEnd;
- (MAAnnotationView *)annotationView;
- (MAPointAnnotation *)annotation;
- (void)setActive:(BOOL)active;
- (void)setMapView:(AMapView *)mapView;
- (void)lockToScreen:(int)x y:(int)y;
@end
#import <React/UIView+React.h>
#import "AMapMarker.h"
#pragma ide diagnostic ignored "OCUnusedMethodInspection"
#pragma clang diagnostic ignored "-Woverriding-method-mismatch"
@implementation AMapMarker {
MAPointAnnotation *_annotation;
MAAnnotationView *_annotationView;
UIView *_customView;
__weak AMapView *_mapView;
MAPinAnnotationColor _pinColor;
UIImage *_image;
CGPoint _centerOffset;
BOOL _draggable;
BOOL _active;
BOOL _canShowCallout;
BOOL _enabled;
NSInteger _zIndex;
}
- (instancetype)init {
_annotation = [MAPointAnnotation new];
_enabled = YES;
_canShowCallout = YES;
self = [super init];
return self;
}
- (NSString *)title {
return _annotation.title;
}
- (NSString *)subtitle {
return _annotation.subtitle;
}
- (CLLocationCoordinate2D)coordinate {
return _annotation.coordinate;
}
- (void)setTitle:(NSString *)title {
_annotation.title = title;
}
- (void)setColor:(MAPinAnnotationColor)color {
_pinColor = color;
((MAPinAnnotationView *) _annotationView).pinColor = color;
}
- (void)setDraggable:(BOOL)draggable {
_draggable = draggable;
_annotationView.draggable = draggable;
}
- (void)setCenterOffset:(CGPoint)centerOffset {
_centerOffset = centerOffset;
_annotationView.centerOffset = centerOffset;
}
- (void)setImage:(NSString *)name {
_image = [UIImage imageNamed:name];
if (_image != nil) {
_annotationView.image = _image;
}
}
- (void)setDescription:(NSString *)description {
_annotation.subtitle = description;
}
- (void)setCoordinate:(CLLocationCoordinate2D)coordinate {
_annotation.coordinate = coordinate;
}
- (void)setActive:(BOOL)active {
_active = active;
dispatch_async(dispatch_get_main_queue(), ^{
if (active) {
[_mapView selectAnnotation:_annotation animated:YES];
} else {
[_mapView deselectAnnotation:_annotation animated:YES];
}
});
}
- (void)setInfoWindowDisabled:(BOOL)disabled {
_canShowCallout = !disabled;
_annotationView.canShowCallout = !disabled;
}
- (void)setClickDisabled:(BOOL)disabled {
_enabled = !disabled;
_annotationView.enabled = !disabled;
}
- (void)setZIndex:(NSInteger)zIndex {
_zIndex = zIndex;
_annotationView.zIndex = zIndex;
}
- (MAPointAnnotation *)annotation {
return _annotation;
}
- (void)setMapView:(AMapView *)mapView {
_mapView = mapView;
}
- (void)_handleTap:(UITapGestureRecognizer *)recognizer {
[_mapView selectAnnotation:_annotation animated:YES];
}
- (MAAnnotationView *)annotationView {
if (_annotationView == nil) {
if (_customView) {
if ([_customView isKindOfClass:[AMapCallout class]]) {
_customView.hidden = NO;
_customView.center = CGPointMake(_customView.center.x, 200);
_annotationView = [[MAAnnotationView alloc] initWithAnnotation:_annotation reuseIdentifier:nil];
_annotationView.bounds = CGRectMake(_customView.bounds.origin.x, _customView.bounds.origin.y - 100, _customView.bounds.size.width + 100, _customView.bounds.size.height + 100);;
[_annotationView addSubview:_customView];
} else {
_customView.hidden = NO;
_annotationView = [[MAAnnotationView alloc] initWithAnnotation:_annotation reuseIdentifier:nil];
_annotationView.bounds = _customView.bounds;
[_annotationView addSubview:_customView];
[_annotationView addGestureRecognizer:[
[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_handleTap:)]];
}
} else {
_annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:_annotation reuseIdentifier:nil];
((MAPinAnnotationView *) _annotationView).pinColor = _pinColor;
}
_annotationView.enabled = _enabled;
_annotationView.canShowCallout = _canShowCallout;
_annotationView.draggable = _draggable;
_annotationView.centerOffset = _centerOffset;
if (_zIndex) {
_annotationView.zIndex = _zIndex;
}
if (_image != nil) {
_annotationView.image = _image;
}
[self setActive:_active];
}
return _annotationView;
}
- (void)didAddSubview:(UIView *)subview {
if ([subview isKindOfClass:[AMapCallout class]]) {
_customView = subview;
_customView.hidden = YES;
} else {
_customView = subview;
_customView.hidden = YES;
}
}
- (void)lockToScreen:(int)x y:(int)y {
_annotation.lockedToScreen = YES;
_annotation.lockedScreenPoint = CGPointMake(x, y);
}
@end
#import <React/RCTUIManager.h>
#import "AMapMarker.h"
#pragma ide diagnostic ignored "OCUnusedClassInspection"
@interface AMapMarkerManager : RCTViewManager
@end
@implementation AMapMarkerManager {
}
RCT_EXPORT_MODULE()
- (UIView *)view {
return [AMapMarker new];
}
RCT_EXPORT_VIEW_PROPERTY(coordinate, CLLocationCoordinate2D)
RCT_EXPORT_VIEW_PROPERTY(centerOffset, CGPoint)
RCT_EXPORT_VIEW_PROPERTY(title, NSString)
RCT_EXPORT_VIEW_PROPERTY(description, NSString)
RCT_EXPORT_VIEW_PROPERTY(active, BOOL)
RCT_EXPORT_VIEW_PROPERTY(draggable, BOOL)
RCT_EXPORT_VIEW_PROPERTY(clickDisabled, BOOL)
RCT_EXPORT_VIEW_PROPERTY(infoWindowDisabled, BOOL)
RCT_EXPORT_VIEW_PROPERTY(zIndex, NSInteger)
RCT_EXPORT_VIEW_PROPERTY(color, MAPinAnnotationColor)
RCT_EXPORT_VIEW_PROPERTY(image, NSString)
RCT_EXPORT_VIEW_PROPERTY(onPress, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onInfoWindowPress, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onDragStart, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onDrag, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onDragEnd, RCTBubblingEventBlock)
RCT_EXPORT_METHOD(lockToScreen:(nonnull NSNumber *)reactTag x:(int)x y:(int)y) {
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
AMapMarker *marker = (AMapMarker *) viewRegistry[reactTag];
[marker lockToScreen:x y:y];
}];
}
RCT_EXPORT_METHOD(active:(nonnull NSNumber *)reactTag) {
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
AMapMarker *marker = (AMapMarker *) viewRegistry[reactTag];
marker.active = YES;
}];
}
@end
#import <MAMapKit/MAOverlayRenderer.h>
@interface AMapOverlay : UIView <MAOverlay>
- (MAOverlayRenderer *)renderer;
@end
#import "AMapOverlay.h"
@implementation AMapOverlay {
}
- (MAOverlayRenderer *)renderer {
return nil;
}
@end
\ No newline at end of file
#import "AMapOverlay.h"
#pragma ide diagnostic ignored "OCUnusedPropertyInspection"
@interface AMapPolygon : AMapOverlay
@property(nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property(nonatomic, readonly) MAMapRect boundingMapRect;
@end
#import "AMapPolygon.h"
#import "Coordinate.h"
#pragma ide diagnostic ignored "OCUnusedMethodInspection"
@implementation AMapPolygon {
MAPolygon *_polygon;
MAPolygonRenderer *_renderer;
CGFloat _strokeWidth;
UIColor *_strokeColor;
UIColor *_fillColor;
}
- (void)setCoordinates:(NSArray<Coordinate *> *)coordinates {
CLLocationCoordinate2D coords[coordinates.count];
for (NSUInteger i = 0; i < coordinates.count; i++) {
coords[i] = coordinates[i].coordinate;
}
_polygon = [MAPolygon polygonWithCoordinates:coords count:coordinates.count];
}
- (void)setStrokeWidth:(CGFloat)strokeWidth {
_strokeWidth = strokeWidth;
_renderer.lineWidth = strokeWidth;
}
- (void)setStrokeColor:(UIColor *)strokeColor {
_strokeColor = strokeColor;
_renderer.strokeColor = strokeColor;
}
- (void)setFillColor:(UIColor *)fillColor {
_fillColor = fillColor;
_renderer.fillColor = fillColor;
}
- (CLLocationCoordinate2D)coordinate {
return _polygon.coordinate;
}
- (MAMapRect)boundingMapRect {
return _polygon.boundingMapRect;
}
- (MAOverlayRenderer *)renderer {
if (_strokeColor == nil) {
_strokeColor = UIColor.blackColor;
}
if (_renderer == nil) {
_renderer = [[MAPolygonRenderer alloc] initWithPolygon:_polygon];
_renderer.lineWidth = _strokeWidth;
_renderer.strokeColor = _strokeColor;
_renderer.fillColor = _fillColor;
}
return _renderer;
}
@end
#import <MAMapKit/MAMapView.h>
#import <React/RCTViewManager.h>
#import "AMapPolygon.h"
#pragma ide diagnostic ignored "OCUnusedClassInspection"
@interface AMapPolygonManager : RCTViewManager
@end
@implementation AMapPolygonManager {
}
RCT_EXPORT_MODULE()
- (UIView *)view {
return [AMapPolygon new];
}
RCT_EXPORT_VIEW_PROPERTY(coordinates, CoordinateArray)
RCT_EXPORT_VIEW_PROPERTY(strokeWidth, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(strokeColor, UIColor)
RCT_EXPORT_VIEW_PROPERTY(fillColor, UIColor)
@end
#import <MAMapKit/MAMapKit.h>
@class AMapMarker;
@interface AMapView : MAMapView
@property(nonatomic, copy) RCTBubblingEventBlock onLocation;
@property(nonatomic, copy) RCTBubblingEventBlock onMapPress;
@property(nonatomic, copy) RCTBubblingEventBlock onLongPress;
@property(nonatomic, copy) RCTBubblingEventBlock onStatusChange;
@property(nonatomic, copy) RCTBubblingEventBlock onStatusChangeComplete;
@property(nonatomic) BOOL loaded;
@property(nonatomic) MACoordinateRegion initialRegion;
- (AMapMarker *)getMarker:(id <MAAnnotation>)annotation;
@end
#import <React/UIView+React.h>
#import "AMapView.h"
#import "AMapMarker.h"
#import "AMapOverlay.h"
#import "LocationStyle.h"
#pragma ide diagnostic ignored "OCUnusedMethodInspection"
@implementation AMapView {
NSMutableDictionary *_markers;
MAUserLocationRepresentation *_locationStyle;
}
- (instancetype)init {
_markers = [NSMutableDictionary new];
self = [super init];
return self;
}
- (void)setShowsTraffic:(BOOL)shows {
self.showTraffic = shows;
}
- (void)setLocationEnabled:(BOOL)enabled {
self.showsUserLocation = enabled;
}
- (void)setShowCompass:(BOOL)enabled {
self.showsCompass = enabled;
}
- (void)setCoordinate:(CLLocationCoordinate2D)coordinate {
self.centerCoordinate = coordinate;
}
- (void)setLocationStyle:(LocationStyle *)locationStyle {
if (!_locationStyle) {
_locationStyle = [MAUserLocationRepresentation new];
}
_locationStyle.fillColor = locationStyle.fillColor;
_locationStyle.strokeColor = locationStyle.strokeColor;
_locationStyle.lineWidth = locationStyle.strokeWidth;
_locationStyle.image = locationStyle.image;
[self updateUserLocationRepresentation:_locationStyle];
}
// 如果在地图未加载的时候调用改方法,需要先将 region 存起来,等地图加载完成再设置
- (void)setRegion:(MACoordinateRegion)region {
if (self.loaded) {
super.region = region;
} else {
self.initialRegion = region;
}
}
- (void)didAddSubview:(UIView *)subview {
if ([subview isKindOfClass:[AMapMarker class]]) {
AMapMarker *marker = (AMapMarker *) subview;
marker.mapView = self;
_markers[[@(marker.annotation.hash) stringValue]] = marker;
dispatch_async(dispatch_get_main_queue(), ^{
[self addAnnotation:marker.annotation];
});
}
if ([subview isKindOfClass:[AMapOverlay class]]) {
[self addOverlay:(id <MAOverlay>) subview];
}
}
- (void)removeReactSubview:(id <RCTComponent>)subview {
[super removeReactSubview:subview];
if ([subview isKindOfClass:[AMapMarker class]]) {
AMapMarker *marker = (AMapMarker *) subview;
[self removeAnnotation:marker.annotation];
}
if ([subview isKindOfClass:[AMapOverlay class]]) {
[self removeOverlay:(id <MAOverlay>) subview];
}
}
- (AMapMarker *)getMarker:(id <MAAnnotation>)annotation {
return _markers[[@(annotation.hash) stringValue]];
}
- (void)setFrame:(CGRect)frame{
if (CGRectGetWidth(frame) <= [UIScreen mainScreen].bounds.size.width) {
[super setFrame:frame];
}
}
@end
#import <React/RCTUIManager.h>
#import "AMapView.h"
#import "AMapMarker.h"
#import "AMapOverlay.h"
#pragma ide diagnostic ignored "OCUnusedClassInspection"
#pragma ide diagnostic ignored "-Woverriding-method-mismatch"
@interface AMapViewManager : RCTViewManager <MAMapViewDelegate>
@end
@implementation AMapViewManager
RCT_EXPORT_MODULE()
- (UIView *)view {
AMapView *mapView = [AMapView new];
mapView.frame = [UIScreen mainScreen].bounds;
mapView.centerCoordinate = CLLocationCoordinate2DMake(39.9242, 116.3979);
mapView.zoomLevel = 10;
mapView.delegate = self;
return mapView;
}
RCT_EXPORT_VIEW_PROPERTY(locationEnabled, BOOL)
RCT_REMAP_VIEW_PROPERTY(showsCompass, showCompass, BOOL)
RCT_EXPORT_VIEW_PROPERTY(showsTraffic, BOOL)
RCT_EXPORT_VIEW_PROPERTY(showsBuildings, BOOL)
RCT_EXPORT_VIEW_PROPERTY(zoomLevel, double)
RCT_EXPORT_VIEW_PROPERTY(maxZoomLevel, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(minZoomLevel, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(zoomEnabled, BOOL)
RCT_EXPORT_VIEW_PROPERTY(scrollEnabled, BOOL)
RCT_EXPORT_VIEW_PROPERTY(rotateEnabled, BOOL)
RCT_EXPORT_VIEW_PROPERTY(mapType, MAMapType)
RCT_EXPORT_VIEW_PROPERTY(limitRegion, MACoordinateRegion)
RCT_EXPORT_VIEW_PROPERTY(region, MACoordinateRegion)
RCT_EXPORT_VIEW_PROPERTY(tilt, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(rotation, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(distanceFilter, CLLocationDistance)
RCT_EXPORT_VIEW_PROPERTY(locationStyle, LocationStyle)
RCT_CUSTOM_VIEW_PROPERTY(touchEnable, BOOL, AMapViewManager){
((AMapView*)view).userInteractionEnabled = [json boolValue];
}
RCT_EXPORT_VIEW_PROPERTY(onMapPress, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onLongPress, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onLocation, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onStatusChange, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onStatusChangeComplete, RCTBubblingEventBlock)
RCT_EXPORT_VIEW_PROPERTY(showsUserLocation, BOOL)
RCT_EXPORT_VIEW_PROPERTY(userTrackingMode, NSInteger)
RCT_CUSTOM_VIEW_PROPERTY(coordinate, MKCoordinateRegion, AMapViewManager){
NSLog(@"RCT_CUSTOM_VIEW_PROPERTY");
if(json[@"latitude"] && json[@"longitude"]){
double latitude = ((NSString*)json[@"latitude"]).doubleValue;
double longitude = ((NSString*)json[@"longitude"]).doubleValue;
CLLocationCoordinate2D location = CLLocationCoordinate2DMake(latitude, longitude);
[((AMapView*)view) setCenterCoordinate:location animated:NO];
}
}
RCT_EXPORT_METHOD(animateTo:(nonnull NSNumber *)reactTag params:(NSDictionary *)params duration:(NSInteger)duration) {
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
AMapView *mapView = (AMapView *) viewRegistry[reactTag];
if (params[@"coordinate"]) {
NSDictionary *coordinate = params[@"coordinate"];
CLLocationCoordinate2D location = CLLocationCoordinate2DMake([coordinate[@"latitude"] doubleValue],
[coordinate[@"longitude"] doubleValue]);
[mapView setCenterCoordinate:location animated:NO];
}
}];
}
- (void)mapView:(AMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate {
if (mapView.onMapPress) {
mapView.onMapPress(@{
@"latitude": @(coordinate.latitude),
@"longitude": @(coordinate.longitude),
});
}
}
- (void)mapView:(AMapView *)mapView didLongPressedAtCoordinate:(CLLocationCoordinate2D)coordinate {
if (mapView.onLongPress) {
mapView.onLongPress(@{
@"latitude": @(coordinate.latitude),
@"longitude": @(coordinate.longitude),
});
}
}
- (void)mapView:(AMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
if (mapView.onLocation) {
mapView.onLocation(@{
@"latitude": @(userLocation.coordinate.latitude),
@"longitude": @(userLocation.coordinate.longitude),
@"accuracy": @((userLocation.location.horizontalAccuracy + userLocation.location.verticalAccuracy) / 2),
@"altitude": @(userLocation.location.altitude),
@"speed": @(userLocation.location.speed),
@"timestamp": @(userLocation.location.timestamp.timeIntervalSince1970),
});
}
}
- (MAAnnotationView *)mapView:(AMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
AMapMarker *marker = [mapView getMarker:annotation];
return marker.annotationView;
}
return nil;
}
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay {
if ([overlay isKindOfClass:[AMapOverlay class]]) {
return ((AMapOverlay *) overlay).renderer;
}
return nil;
}
- (void)mapView:(AMapView *)mapView didAnnotationViewTapped:(MAAnnotationView *)view
{
AMapMarker *marker = [mapView getMarker:view.annotation];
if (marker.onPress) {
marker.onPress(nil);
}
}
- (void)mapView:(AMapView *)mapView didAnnotationViewCalloutTapped:(MAAnnotationView *)view {
AMapMarker *marker = [mapView getMarker:view.annotation];
if (marker.onInfoWindowPress) {
marker.onInfoWindowPress(nil);
}
}
- (void)mapView:(AMapView *)mapView annotationView:(MAAnnotationView *)view didChangeDragState:(MAAnnotationViewDragState)newState
fromOldState:(MAAnnotationViewDragState)oldState {
AMapMarker *marker = [mapView getMarker:view.annotation];
if (newState == MAAnnotationViewDragStateStarting && marker.onDragStart) {
marker.onDragStart(nil);
}
if (newState == MAAnnotationViewDragStateDragging) {
if (marker.onDrag) {
marker.onDrag(nil);
}
}
if (newState == MAAnnotationViewDragStateEnding && marker.onDragEnd) {
marker.onDragEnd(@{
@"latitude": @(marker.annotation.coordinate.latitude),
@"longitude": @(marker.annotation.coordinate.longitude),
});
}
}
- (void)mapViewRegionChanged:(AMapView *)mapView {
if (mapView.onStatusChange) {
MACoordinateRegion status = mapView.region;
mapView.onStatusChange(@{
@"latitude": @(status.center.latitude),
@"longitude": @(status.center.longitude),
});
}
}
- (void)mapView:(AMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
if (mapView.onStatusChangeComplete) {
MACoordinateRegion status = mapView.region;
mapView.onStatusChangeComplete(@{
@"latitude": @(status.center.latitude),
@"longitude": @(status.center.longitude),
@"latitudeDelta": @(status.span.latitudeDelta),
@"longitudeDelta": @(status.span.longitudeDelta),
});
}
}
- (void)mapInitComplete:(AMapView *)mapView {
mapView.loaded = YES;
// struct 里的值会被初始化为 0,这里以此作为条件,判断 initialRegion 是否被设置过
// 但实际上经度为 0 是一个合法的坐标,只是考虑到高德地图只在中国使用,就这样吧
if (mapView.initialRegion.center.latitude != 0) {
mapView.region = mapView.initialRegion;
}
}
@end
require 'json'
package = JSON.parse(File.read(File.join(__dir__, '../package.json')))
Pod::Spec.new do |s|
s.name = "react-native-amap-sdk"
s.version = "2.0.1"
s.summary = package['description']
s.description = <<-DESC
React Native apps are built using the React JS
framework, and render directly to native UIKit
elements using a fully asynchronous architecture.
There is no browser and no HTML. We have picked what
we think is the best set of features from these and
other technologies to build what we hope to become
the best product development framework available,
with an emphasis on iteration speed, developer
delight, continuity of technology, and absolutely
beautiful and fast products with no compromises in
quality or capability.
DESC
s.homepage = "http://git.terminus.io/reactnastive/RNAMapLocation"
s.license = package['license']
s.author = "Jianglei"
s.source = { :git => "git.terminus.io:reactnative/RNAMapLocation.git", :tag => "v#{s.version}" }
s.requires_arc = true
s.platform = :ios, "7.0"
s.preserve_paths = "*.framework"
s.subspec 'LocationAmap' do |ls|
ls.source_files = 'location/**/*.{h,m}'
ls.dependency 'libextobjc'
ls.dependency 'AMapSearch'
ls.dependency 'AMapLocation'
end
s.subspec 'Map3dAmap' do |ms|
ms.source_files = 'map3damap/**/*.{h,m}'
ms.dependency 'AMap2DMap', "~> 5.6.0"
end
s.dependency 'React'
end
import * as Location from './index'
module.exports = Location
\ No newline at end of file
{
"presets": ["es2015", "stage-0", "react"]
}
\ No newline at end of file
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# http://editorconfig.org
root = true
[**]
# 文件结尾符
end_of_line = lf
insert_final_newline = true
# 去除行尾空白字符
trim_trailing_whitespace = true
# 编码格式
charset = utf-8
# 项目中采用tab作为代码缩进样式
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false
[{package.json,.babelrc,.eslintrc}]
indent_style = space
indent_size = 2
[*.yml]
indent_style = space
indent_size = 2
\ No newline at end of file
{
"env": {
"es6": true
},
"plugins": ["react", "flowtype"],
"extends": ["elemefe", "plugin:flowtype/recommended"],
"parser": "babel-eslint",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
"react/jsx-uses-react": "error",
"react/jsx-uses-vars": "error",
"semi": "off"
},
"settings": {
"flowtype": {
"onlyFilesWithFlowAnnotation": false
}
}
}
# react-amap Contributing Guide
Hi! Thank you for choosing react-amap.
React-amap is a Map Components Based On React and AMap(amap.com)
We are excited that you are interested in contributing to react-amap. Before submitting your contribution though, please make sure to take a moment and read through the following guidelines.
## Issue Guidelines
- Issues are exclusively for bug reports and feature requests. Other questions may be closed directly.
- Before submitting an issue, please check if similar problems have already been issued.
- Please specify which version of react-amap you are using, and provide OS and browser information. [JSFiddle](https://jsfiddle.net/) is recommended to build a live demo so that your issue can be reproduced clearly.
## Pull Request Guidelines
- Fork this repository to your own account. Do not create branches here.
- **DO NOT** include files inside `lib` directory.
- Rebase before creating a PR to keep commit history clear.
- If you are fixing a bug, please include detailed description of the bug in the PR.
- Merging a PR takes two maintainers: one approves the changes after reviewing, and then the other reviews and merges.
## Code Style
Just comply with the [ESLint](https://github.com/ElemeFE/eslint-config-elemefe) configuration of [ElemeFE](https://github.com/elemefe).
# react-amap Contributing Guide
Hi! 首先感谢你使用 react-amap。
react-amap 是一个基于 React 封装的高德地图组件库。
react-amap 的成长离不开大家的支持,如果你愿意为 react-amap 贡献代码或提供建议,请阅读以下内容。
## Issue 规范
- issue 仅用于提交 Bug 或 Feature,其它内容可能会被直接关闭。
- 在提交 issue 之前,请搜索相关内容是否已被提出。
- 请说明 react-amap 的版本号,并提供操作系统和浏览器信息。推荐使用 [JSFiddle](https://jsfiddle.net/) 生成在线 demo,这能够更直观地重现问题。
## Pull Request 规范
- 请先 fork 一份到自己的项目下,不要直接在仓库下建分支。
- **不要提交** `lib` 里面打包的文件。
- 提交 PR 前请 rebase,确保 commit 记录的整洁。
- 如果是修复 bug,请在 PR 中给出描述信息。
- 合并代码需要两名维护人员参与:一人进行 review 后 approve,另一人再次 review,通过后即可合并。
## 代码规范
遵循饿了么前端的 [ESLint](https://github.com/ElemeFE/eslint-config-elemefe) 即可
<!--
请确保阅读下面的内容并勾选。没有勾选的 Issue 将被关闭。
-->
+ [ ] 我已经搜索过 issue,没有类似的问题,或者类似的问题仍然没有解决方案。
+ [ ] 我已经搜索过[文档](https://elemefe.github.io/react-amap/articles/start),并且仍然没有找到解决方案。
+ [ ] 我写了个问题重现的例子,链接或者代码将会贴在下面。
<!--
请确保阅读上面的内容并勾选。没有勾选的 Issue 将被关闭。
-->
#### Reproduce Example Link or Code Fragment
#### What is Expected?
#### What is actually happening?
Please makes sure these boxes are checked before submitting your PR, thank you!
* [ ] Make sure you follow the contributing guide.
* [ ] Rebase before creating a PR to keep commit history clear.
* [ ] Add some descriptions and refer relative issues for you PR.
language: node_js
node_js:
- "6"
branched:
only:
- master
script:
- npm run lint
- npm run browser-build
- npm run site
# 更新日志
## [2017-12-13] 1.2.0
### 更新
1. 对除 Markers 以外的其他组件都进行了重构;重构效果如下:
1. 抽出了共用的逻辑代码,这部分代码以 HOC 注入到组件中;
2. 重构后的组件 events 属性响应式的;
3. 组件属性变更时对实例的操作更加智能;(比如对名为 offset 的属性进行修改,会尝试执行 setOffset 方法)
4. 允许用户自己选择高德地图版本(Map 组件的 version 属性);
5. 对外使用的接口不变,所以可以无痛升级。
### 修复
1. 使用 CDN 接入 react-amap 资源时 Marker 组件有个严重的 Bug,不过似乎没人发现,不管了反正已经偷偷修好了。
---
## [2017-11-16] 1.1.2
### 更新
1. Map 组件卸载时自动销毁地图实例对象。
---
## [2017-11-13] 1.1.1
### 更新
1. 重构 APILoader 类,支持加载 AMapUI 组件库。
---
## [2017-10-13] 1.1.0
### 更新
1. 大幅重构 Map 组件;支持 `animateEnable``doubleClickZoom` 等属性的动态配置。
2. 支持 3D 模式。
3. 新增控件 ControlBar。
4. 删除了地图内层一个多余的 div。([#48](https://github.com/ElemeFE/react-amap/issues/48)
3. 支持给 Map 提供 loading 组件以渲染加载效果。
2. 支持给 Marker 组件添加 `className`。([#40](https://github.com/ElemeFE/react-amap/issues/40)
3. 补充了 TypeScript 模块声明,可以在 TypeScript 项目中使用。([#47](https://github.com/ElemeFE/react-amap/issues/47)
---
## [2017-08-14] 1.0.3
### 修复
* 修复部分组件在 unmount 后并没有从地图消失的问题。
---
## [2017-06-14] 1.0.0
### 重大更新
* 现在 react-amap 拥有了扩展能力,你可以自己写一个地图组件并且在 Map 中嵌入;相关文档请参考[自定义地图组件](https://elemefe.github.io/react-amap/articles/extend)
---
## [2017-05-11] 0.2.7
### 优化
* 唯一使用了样式的 Markers 组件,直接把样式写在代码里,不需要为了这个额外引入 css-loader 之类的插件进行打包。
---
## [2017-04-13] 0.2.6
### 优化
* 优化打包方式;支持组件的单个 import
---
## [2017-04-11] 0.2.5
### 修复
* 在同构 SSR 架构的应用中确保不抛出错误
---
## [2017-03-22] 0.2.4-0
### 修复
* 在刷新 Markers 时,把之前存在的标记清空
---
## [2017-03-22] 0.2.3
### 新增
* 新增 [MouseTool](https://elemefe.github.io/react-amap/components/mousetool) 鼠标工具插件;通过该插件,可进行鼠标画标记点、线、多边形、矩形、圆、距离量测、面积量测、拉框放大、拉框缩小等功能。
---
## [2017-03-16] 0.2.3-0
### 修复
* 因为 React 框架的限制,`key` 属性另有所用,所以定义高德的 Key 时统一为 `amapkey`。详见[关于 key](https://elemefe.github.io/react-amap/articles/start#关于-key)
---
## [2017-03-16] 0.2.2
### 新增
* Marker 组件新增可以定义 render 静态属性渲染外观;也在高德 Marker 实例挂载 render 方法动态渲染外观。
---
## [2017-03-15] 0.2.1
### 优化
* 重新设计 Markers 接口,对标记的外观控制更灵活;本次更新不向下兼容。
---
## [2017-03-14] 0.2.0
### 优化
* 所有组件接口(除 Markers)重新设计,开发者可以通过绑定事件获得高德原生实例。
---
## [2017-02-23] 0.0.1-rc.1
### react-amap 发布
MIT License
Copyright (c) 2017 ElemeFE
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
<img src="https://cloud.githubusercontent.com/assets/3898898/23833571/e5c7ae68-0782-11e7-8590-cecf4f3c969f.png" width="118" height="118" />
# react-amap
[![Build Status](https://travis-ci.org/ElemeFE/react-amap.svg?branch=master)](https://travis-ci.org/ElemeFE/react-amap)
[![npm version](https://badge.fury.io/js/react-amap.svg?_t=20170411)](https://www.npmjs.com/package/react-amap)
[![npm downloads](https://img.shields.io/npm/dm/react-amap.svg)](https://www.npmjs.com/package/react-amap)
> react-amap 是一个基于 React 封装的高德地图组件;帮助你轻松的接入地图到 React 项目中。除了必须引用的 Map 组件外,我们目前提供了最常用的 10 个地图组件,能满足大部分简单的业务场景;如果你有更复杂的需求,或者觉得默认提供的组件功能不够,你完全可以自定义一个地图组件,然后根据高德原生 API 做高德允许你做的一切事情。
### 最近更新
react-amap 升级到 1.1.1,支持加载 [AMapUI 组件库](http://lbs.amap.com/api/javascript-api/guide/amap-ui/intro)。加载方式参考 [Map 组件](/components/map) 关于 **加载 AMapUI 组件库** 的说明。(2017-11-13)
### 扩展组件
从版本 [1.0.0](https://www.npmjs.com/package/react-amap) 开始,react-amap 拥有了组件的扩展能力。如果 react-amap 中已有的组件不能满足你的业务需求,你可以使用自己写的地图组件;
在你的组件中,可以通过 props 访问到创建好的高德地图实例,以及地图的 div 容器;拥有访问这两个属性的能力后,你可以根据高德原生 API 做高德允许你做的一切事情。实际上,react-amap 中的其他组件就是这么做的。文档内容请参考[自定义地图组件](https://elemefe.github.io/react-amap/articles/extend)
目前已有的一些组件:
1. [react-amap-plugin-heatmap](https://www.npmjs.com/package/react-amap-plugin-heatmap),热力图组件。
2. [react-amap-plugin-geolocation](https://www.npmjs.com/package/react-amap-plugin-geolocation),定位组件。
3. [react-amapui-wrapper](https://github.com/Croash/react-amapui-wrapper),可自定义的AMapUI组件。
如果你有写好的组件愿意开源出来的,欢迎提一个 PR 扩展这个列表。
### 在线实时演示
https://jsfiddle.net/ioslh/h4u8mdng/25/
---
如何在项目中接入 react-amap;
### 安装
```sh
npm install --save react-amap
```
### npm 用法
```html
<div id="app"></div>
```
```css
#app {
width: 600px;
height: 400px;
}
```
```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { Map } from 'react-amap';
ReactDOM.render(
<Map amapkey={YOUR_AMAP_KEY} version={VERSION} />,
document.querySelector('#app')
)
```
amapkey 说明见下文
version 指定高德地图版本 不填则使用默认值: 1.4.0
也可以手工引入你需要的组件:
```jsx
import Map from 'react-amap/lib/map';
import Marker from 'react-amap/lib/marker';
// ... your other code
```
以上为简单场景的应用。
**tips:** Map 组件的父元素须设置高度和宽度;关于代码中的 `Map` 组件的 `amapkey` 属性见下方的说明。
### CDN 用法
在 HTML 页面中加入 react-amap 库的 CDN 地址,插件会在 `window` 下暴露 `ReactAMAP` 变量。
```html
<script src="path/to/react.js"></script>
<script src="path/to/react-dom.js"></script>
<script src="path/to/dist/react-amap.js"></script>
<script>
var Map = ReactAMAP.Map;
var Marker = ReactAMAP.Marker;
var pos = { longitude: 120, latitude: 30 };
var YourApp = React.createElement(
Map,
{ center: pos },
React.createElement(
Marker,
{ position: pos },
null
)
);
ReactDOM.render(YourApp, document.getElementById('root'));
</script>
```
##### CDN 地址
实际应用中你可以使用下面的 CDN 地址,也可以把脚本下载下来本地部署。
tips: 记得将其中的 `VERSION` 替换为真实版本号,查看历史版本[更新日志](https://elemefe.github.io/react-amap/articles/changelog)。
+ https://unpkg.com/react-amap@VERSION/dist/react-amap.js
+ https://unpkg.com/react-amap@VERSION/dist/react-amap.min.js
### 关于 Key
在上面的例子中需要给 Map 组件传入 `amapkey` 属性,这个是高德地图给开发者分配的开发者 Key;你可以在[高德开放平台](http://lbs.amap.com/faq/account/key/67)申请你自己的 Key。
在 react-amap 中 Key 的传入方式有两种:
+ 给 Map 组件传入 `amapkey` 属性(因为 React 框架本身对 `key` 属性有其他作用,所以不能用 `key`,所以我们用 `amapkey`),这样的缺点是如果多个地方使用就要每次都要传入;
+ 你也可以定义一个纯组件,把 Map 组件的 amapkey 属性写好后返回新组件。
+ 直接把你的 Key 定义在全局变量 `window.amapkey` 上,react-amap 在调用高德接口时会尝试从这里读取。(不推荐)
组件的使用请移步[组件文档](https://elemefe.github.io/react-amap/components/about)。
### 贡献指南
首先感谢你使用 react-amap,react-amap 是一个基于 React 封装的高德地图组件库。
react-amap 的成长离不开大家的支持,如果你愿意为 react-amap 贡献代码或提供建议,请阅读以下内容。
#### 开发
```shell
npm install
npm start # http://localhost:9001
```
#### Issue 规范
- issue 仅用于提交 Bug 或 Feature,其它内容可能会被直接关闭。
- 在提交 issue 之前,请搜索相关内容是否已被提出。
- 在提交issue时,请说明 react-amap 的版本号,并提供操作系统和浏览器信息。推荐使用 [JSFiddle](https://jsfiddle.net/ioslh/mxc0h16p/5/) 生成在线 demo,这能够更直观地重现问题。
#### Pull Request 规范
- 请先 fork 一份到自己的项目下,不要直接在仓库下建分支。
- **不要提交 `dist` 里面打包的文件**
- 提交 PR 前请 rebase,确保 commit 记录的整洁。
- 如果是修复 bug,请在 PR 中给出描述信息。
- 合并代码需要两名维护人员参与:一人进行 review 后 approve,另一人再次 review,通过后即可合并。
### 代码规范
遵循饿了么前端的 [ESLint](https://github.com/ElemeFE/eslint-config-elemefe) 即可。
### License
[MIT License](https://github.com/ElemeFE/react-amap/blob/master/COPYING)
Copyright (c) 2017 ElemeFE
This source diff could not be displayed because it is too large. You can view the blob instead.
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports.ReactAMAP=t(require("react"),require("react-dom")):e.ReactAMAP=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=8)}([function(t,n){t.exports=e},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r={MARKER_ID_CONFLICT:"Marker 的 id 属性重复",MARKER_ID_REQUIRED:"每一个 Marker 必需有一个 id 属性",MAP_INSTANCE_REQUIRED:"没有地图实例;组件必须作为 Map 的子组件使用",CIRCLE_INSTANCE_REQUIRED:"",CIRCLE_CENTER_REQUIRED:"Circle 组件必需设置 center 属性",CIRCLE_RADIUS_REQUIRED:"Circle 组件必需设置 radius 属性",SRC_REQUIRED:"GroundImage 组件必需设置 src 属性",BOUNDS_REQUIRED:"GroundImage 组件必需设置 bounds 属性",WINDOW_POSITION_REQUIRED:"InfoWindow 组件必需设置 position 属性",INVALID_AMAP_PLUGIN:"plugins 属性不正确;目前支持的插件有'Scale', 'ToolBar', 'MapType', 'OverView'"},o=function(e){return e in r?r[e]:e},i={error:function(e){throw new Error(o(e))},warning:function(e){console.warn(o(e))},optimize:function(e){console.log("%c"+o(e),"color:#d4d483;border-left: 2px solid #d4d483;padding-left: 4px;")}};t.default=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e){return function(t){function n(e){o(this,n);var t=i(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t.instanceCreated=!1,t.myMapComponent=null,t.registeredEvents=[],t.onInstanceCreated=t.onInstanceCreated.bind(t),t}return a(n,t),s(n,[{key:"onInstanceCreated",value:function(){if(this.instanceCreated=!0,"events"in this.props){var e=this.myMapComponent.instance;this.props.events.created&&this.props.events.created(e)}this.reactivePropChange(this.props,!1)}},{key:"createEventsProxy",value:function(e){var t=this,n=this.myMapComponent.instance,r=Object.keys(e.events||{});r.length&&r.forEach(function(e){-1===t.registeredEvents.indexOf(e)&&(t.registeredEvents.push(e),n.on(e,function(e){return function(){if(t.props.events&&e in t.props.events){for(var n=arguments.length,r=Array(n),o=0;o<n;o++)r[o]=arguments[o];t.props.events[e].apply(null,r)}}}(e)))})}},{key:"componentWillReceiveProps",value:function(e){this.reactivePropChange(e,!0)}},{key:"reactivePropChange",value:function(e){var t=this,n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this.instanceCreated)return!1;var r=this.myMapComponent,o=r.setterMap,i=void 0===o?{}:o,a=r.converterMap,u=void 0===a?{}:a,l=r.instance,s=void 0===l?{}:l,c=Object.keys(e);c.length&&c.forEach(function(r){if("events"===r)return t.createEventsProxy(e);var o=!0;if(n&&(o=t.detectPropChange(r,e,t.props)),!o)return!1;var a=e[r];if(r in u&&(a=u[r](e[r])),r in i)i[r](a);else{var l="set"+(0,d.default)(r);l in s&&s[l](a)}})}},{key:"detectPropChange",value:function(e,t,n){return t[e]!==n[e]}},{key:"render",value:function(){var t=this;return f.default.createElement(e,l({onInstanceCreated:this.onInstanceCreated,ref:function(e){t.myMapComponent=e}},this.props))}},{key:"componentWillUnmount",value:function(){var e=this.myMapComponent.instance;e&&("destroy"in e&&setTimeout(function(){e.destroy()},10),"hide"in e&&e.hide(),"__map__"in this.props&&"setMap"in e&&e.setMap(null))}}]),n}(f.default.Component)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=n(0),f=r(c),p=n(11),d=r(p);t.default=u},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r="undefined"!=typeof window,o=t.toLnglat=function(e){if(!e)return e;if("getLng"in e&&"getLat"in e)return e;var t=0,n=0;return"[object Array]"==={}.toString.call(e)?(t=e[0],n=e[1]):"lng"in e&&"lat"in e?(t=e.lng,n=e.lat):"longitude"in e&&"latitude"in e&&(t=e.longitude,n=e.latitude),r?new window.AMap.LngLat(t,n):null},i=t.toPixel=function(e){if(!e)return e;if("getX"in e&&"getY"in e)return e;var t=0,n=0;return"[object Array]"==={}.toString.call(e)?(t=e[0],n=e[1]):"x"in e&&"y"in e&&(t=e.x,n=e.y),r?new window.AMap.Pixel(t,n):null},a=t.toSize=function(e){return e?"getWidth"in e?e:r?new window.AMap.Size(e.width,e.height):null:e};t.default={toLnglat:o,toPixel:i,toSize:a}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(e){return!!e&&"function"==typeof e};t.default=r},function(e,n){e.exports=t},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=n(0),s=r(l),c=n(2),f=r(c),p=n(1),d=r(p),h=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));if("undefined"!=typeof window)if(e.__map__&&e.__poly__){var r=n;n.setterMap={active:function(e){r.toggleActive(e)}},n.map=e.__map__,n.poly=e.__poly__,n.editorActive=!1,n.createEditorInstance().then(function(){n.props.onInstanceCreated&&n.props.onInstanceCreated()})}else d.default.warning("MAP_INSTANCE_REQUIRED");return n}return a(t,e),u(t,[{key:"toggleActive",value:function(e){e?this.editorActive||this.activeEditor():this.editorActive&&this.inactiveEditor()}},{key:"activeEditor",value:function(){this.polyEditor&&(this.editorActive=!0,this.polyEditor.open())}},{key:"inactiveEditor",value:function(){this.editorActive=!1,this.polyEditor&&this.polyEditor.close()}},{key:"createEditorInstance",value:function(){var e=this;return this.polyEditor?Promise.resolve(this.polyEditor):new Promise(function(t){e.map.plugin(["AMap.PolyEditor"],function(){e.polyEditor=new window.AMap.PolyEditor(e.map,e.poly),t(e.polyEditor)})})}},{key:"render",value:function(){return null}},{key:"instance",get:function(){return this.polyEditor}}]),t}(s.default.Component);t.default=(0,f.default)(h)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.renderMarkerComponent=t.getPropValue=t.MarkerAllProps=t.MarkerConfigurableProps=void 0;var o=n(3),i=n(0),a=r(i),u=n(5),l=n(4),s=r(l),c=t.MarkerConfigurableProps=["position","offset","icon","content","draggable","visible","zIndex","angle","animation","shadow","title","clickable","extData","label"],f=t.MarkerAllProps=c.concat(["topWhenClick","bubble","raiseOnDrag","cursor","autoRotation","shape"]);t.getPropValue=function(e,t){return-1===f.indexOf(e)?null:"position"===e?(0,o.toLnglat)(t):"offset"===e?(0,o.toPixel)(t):t},t.renderMarkerComponent=function(e,t){var n=e;if((0,s.default)(e)){n=e(t.getExtData())}n&&(0,u.render)(a.default.createElement("div",null,n),t.getContent())}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.MouseTool=t.Marker=t.GroundImage=t.InfoWindow=t.PolyEditor=t.Polyline=t.Polygon=t.CircleEditor=t.Circle=t.Markers=t.Map=void 0;var o=n(9),i=r(o),a=n(12),u=r(a),l=n(13),s=r(l),c=n(14),f=r(c),p=n(15),d=r(p),h=n(16),v=r(h),y=n(17),m=r(y),b=n(18),_=r(b),w=n(19),g=r(w),k=n(6),C=r(k),M=n(20),E=r(M);t.Map=i.default,t.Markers=s.default,t.Circle=f.default,t.CircleEditor=g.default,t.Polygon=d.default,t.Polyline=v.default,t.PolyEditor=C.default,t.InfoWindow=m.default,t.GroundImage=_.default,t.Marker=u.default,t.MouseTool=E.default,t.default={Map:i.default,Markers:s.default,Circle:f.default,CircleEditor:g.default,Polygon:d.default,Polyline:v.default,PolyEditor:C.default,InfoWindow:m.default,GroundImage:_.default,Marker:u.default,MouseTool:E.default}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=n(0),f=r(c),p=n(10),d=r(p),h=n(4),v=r(h),y=n(1),m=r(y),b=n(3),_=n(2),w=r(_),g=f.default.Component,k=f.default.Children,C={width:"100%",height:"100%"},M={width:"100%",height:"100%",position:"relative"},E=["layers","zoom","center","labelzIndex","mapStyle","features","cursor","pitch"],O=["animateEnable","doubleClickZoom","dragEnable","isHotspot","jogEnable","keyboardEnable","resizeEnable","rotateEnable","scrollWheel","touchZoom","zoomEnable"],P=["view","zooms","showIndoorMap","indoorMap","expandZoomRange","showBuildingBlock","viewMode","pitchEnable","buildingAnimation","skyColor"],I=E.concat(O,P),j={MapType:{showRoad:!1,showTraffic:!1,defaultType:0},ToolBar:{position:"RB",noIpLocate:!0,locate:!0,liteStyle:!0,autoPosition:!1},OverView:{},ControlBar:{}},A=function(e){function t(e){i(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.state={mapLoaded:!1};var r=n;return n.setterMap={zoom:function(e){r.map.setZoom(e)},cursor:function(e){r.map.setDefaultCursor(e)},labelzIndex:function(e){r.map.setlabelzIndex(e)}},n.converterMap={center:b.toLnglat},"undefined"!=typeof window&&(n.pluginMap={},new d.default({key:e.amapkey,useAMapUI:e.useAMapUI,version:e.version,protocol:e.protocol}).load().then(function(){n.createInstance(),n.state.mapLoaded||n.setState({mapLoaded:!0})})),n}return u(t,e),s(t,[{key:"componentWillReceiveProps",value:function(e){this.state.mapLoaded&&this.updateMapProps(this.props,e)}},{key:"renderChildren",value:function(){var e=this;return k.map(this.props.children,function(t){if(t){var n=t.type;return n.preventAmap||"string"==typeof n?t:f.default.cloneElement(t,{__map__:e.map})}return t})}},{key:"createInstance",value:function(){if(!this.map){var e=this.buildCreateOptions();this.map=new window.AMap.Map(this.mapWrapper,e),this.setPlugins(this.props),this.props.onInstanceCreated&&this.props.onInstanceCreated()}}},{key:"buildCreateOptions",value:function(){var e=this,t=this.props,n={};return I.forEach(function(r){r in t&&(n[r]=e.getSetterValue(r,t))}),n}},{key:"updateMapProps",value:function(e,t){var n=this,r={},o=!1,i=!1;O.forEach(function(a){a in t&&(i=!0,n.detectPropChanged(a,e,t)&&(o=!0,r[a]=t[a]))}),o&&this.map.setStatus(r),i&&"status"in t&&m.default.warning("以下这些属性可以单独提供进行配置,也可以统一作为‘status’属性配置;但是请不要同时使用这两种方式。\n("+O.join(", ")+")"),P.forEach(function(r){r in t&&n.detectPropChanged(r,e,t)&&m.default.warning("'"+r+"' 是一个静态属性,地图实例创建成功后无法修改")}),this.setPlugins(t)}},{key:"getSetterValue",value:function(e,t){return e in this.converterMap?this.converterMap[e](t[e]):t[e]}},{key:"detectPropChanged",value:function(e,t,n){return t[e]!==n[e]}},{key:"setPlugins",value:function(e){var t=this,n=["Scale","ToolBar","MapType","OverView","ControlBar"];if("plugins"in e){var r=e.plugins;r&&r.length&&r.forEach(function(e){var r=void 0,o=void 0,i=void 0;"string"==typeof e?(r=e,o=null,i=!0):(r=e.name,o=e.options||{},i=!("visible"in o&&"boolean"==typeof o.visible)||o.visible,delete o.visible);var a=n.indexOf(r);-1===a?m.default.warning("没有 ‘"+r+"’ 这个插件,请检查是否拼写错误"):i&&(n.splice(a,1),t.installPlugin(r,o))})}this.removeOrDisablePlugins(n)}},{key:"removeOrDisablePlugins",value:function(e){var t=this;e&&e.length&&e.forEach(function(e){e in t.pluginMap&&("ControlBar"===e?(t.map.removeControl(t.pluginMap[e]),delete t.pluginMap[e]):t.pluginMap[e].hide())})}},{key:"installPlugin",value:function(e,t){switch(t=t||{},e){case"Scale":case"ToolBar":case"OverView":case"MapType":this.setMapPlugin(e,t);break;case"ControlBar":this.setControlBar(t)}}},{key:"setMapPlugin",value:function(e,t){var n=this;if(this.pluginMap[e])this.pluginMap[e].show();else{var r=t.onCreated,i=o(t,["onCreated"]),a=l({},j[e],i);this.map.plugin(["AMap."+e],function(){n.pluginMap[e]=new window.AMap[e](a),n.map.addControl(n.pluginMap[e]),(0,v.default)(r)&&r(n.pluginMap[e])})}}},{key:"setControlBar",value:function(e){var t=this;if(this.pluginMap.ControlBar);else{var n=e.onCreated,r=o(e,["onCreated"]),i=l({},j.ControlBar,r);this.map.plugin(["AMap.ControlBar"],function(){t.pluginMap.ControlBar=new window.AMap.ControlBar(i),t.map.addControl(t.pluginMap.ControlBar),(0,v.default)(n)&&n(t.pluginMap.ControlBar)})}}},{key:"render",value:function(){var e=this;return f.default.createElement("div",{style:M},f.default.createElement("div",{ref:function(t){e.mapWrapper=t},style:C},this.state.mapLoaded?null:this.props.loading||null),f.default.createElement("div",null,this.state.mapLoaded?this.renderChildren():null))}},{key:"instance",get:function(){return this.map}}]),t}(g);t.default=(0,w.default)(A)},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a={v:"1.4.0",hostAndPath:"webapi.amap.com/maps",key:"f97efc35164149d0c0f299e7a8adb3d2",callback:"__amap_init_callback",useAMapUI:!1},u=null,l=null,s=!1,c=function(){function e(t){var n=t.key,i=t.useAMapUI,u=t.version,l=t.protocol;r(this,e),this.config=o({},a,{useAMapUI:i,protocol:l}),"undefined"!=typeof window&&(n?this.config.key=n:"amapkey"in window&&(this.config.key=window.amapkey)),u&&(this.config.v=u),this.protocol=l||window.location.protocol,-1===this.protocol.indexOf(":")&&(this.protocol+=":")}return i(e,[{key:"getScriptSrc",value:function(e){return this.protocol+"//"+e.hostAndPath+"?v="+e.v+"&key="+e.key+"&callback="+e.callback}},{key:"buildScriptTag",value:function(e){var t=document.createElement("script");return t.type="text/javascript",t.async=!0,t.defer=!0,t.src=e,t}},{key:"getAmapuiPromise",value:function(){var e=this.buildScriptTag(this.protocol+"//webapi.amap.com/ui/1.0/main-async.js"),t=new Promise(function(t){e.onload=function(){t()}});return document.body.appendChild(e),t}},{key:"getMainPromise",value:function(){var e=this,t=this.buildScriptTag(this.getScriptSrc(this.config)),n=new Promise(function(t){window[e.config.callback]=function(){t(),delete window[e.config.callback]}});return document.body.appendChild(t),n}},{key:"load",value:function(){if("undefined"==typeof window)return null;var e=this.config.useAMapUI;return u=u||this.getMainPromise(),e&&(l=l||this.getAmapuiPromise()),new Promise(function(t){u.then(function(){e&&l?l.then(function(){window.initAMapUI&&!s&&(window.initAMapUI(),"function"==typeof e&&e(),s=!0),t()}):t()})})}}]),e}();t.default=c},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(e){return e[0].toUpperCase()+e.slice(1,e.length)};t.default=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=n(0),c=r(s),f=n(5),p=n(1),d=r(p),h=n(2),v=r(h),y=n(7),m=n(3),b=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));if("undefined"!=typeof window)if(e.__map__){var r=n;n.setterMap={visible:function(e){e?r.marker&&r.marker.show():r.marker&&r.marker.hide()},zIndex:function(e){r.marker&&r.marker.setzIndex(e)}},n.converterMap={position:m.toLnglat,offset:m.toPixel},n.map=e.__map__,n.element=n.map.getContainer(),setTimeout(function(){n.createMarker(e)},13)}else d.default.warning("MAP_INSTANCE_REQUIRED");return n}return a(t,e),l(t,[{key:"shouldComponentUpdate",value:function(){return!1}},{key:"componentWillReceiveProps",value:function(e){this.map&&this.refreshMarkerLayout(e)}},{key:"createMarker",value:function(e){var t=this.buildCreateOptions(e);this.marker=new window.AMap.Marker(t),this.marker.render=function(e){return function(t){(0,y.renderMarkerComponent)(t,e)}}(this.marker),this.props.onInstanceCreated&&this.props.onInstanceCreated(),this.setMarkerLayout(e),this.setChildComponent(e)}},{key:"buildCreateOptions",value:function(e){var t=this,n={};return y.MarkerAllProps.forEach(function(r){r in e&&(n[r]=t.getSetterParam(r,e[r]))}),n.map=this.map,n}},{key:"setMarkerLayout",value:function(e){("render"in e||"children"in e&&e.children)&&(this.createContentWrapper(),"className"in e&&e.className&&(this.contentWrapper.className=e.className))}},{key:"createContentWrapper",value:function(){this.contentWrapper=document.createElement("div"),this.marker.setContent(this.contentWrapper)}},{key:"setChildComponent",value:function(e){if(this.contentWrapper)if("className"in e&&e.className&&(this.contentWrapper.className=e.className),"render"in e)(0,y.renderMarkerComponent)(e.render,this.marker);else if("children"in e){var t=e.children,n=void 0===t?"undefined":u(t);"undefined"!==n&&this.contentWrapper&&(0,f.render)(c.default.createElement("div",null,t),this.contentWrapper)}}},{key:"refreshMarkerLayout",value:function(e){this.setChildComponent(e)}},{key:"getSetterParam",value:function(e,t){return e in this.converterMap?this.converterMap[e](t):t}},{key:"render",value:function(){return null}},{key:"instance",get:function(){return this.marker}}]),t}(c.default.Component);t.default=(0,v.default)(b)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=n(0),s=r(l),c=n(5),f=n(4),p=r(f),d=n(1),h=r(d),v=n(7);if("undefined"!=typeof window){var y=document.head||document.getElementsByTagName("head")[0],m=document.createElement("style");m.type="text/css",m.textContent=".amap_markers_pop_window{\n padding: 10px;\n border: 1px solid #ddd;\n border-radius: 8px;\n background: #fff;\n position: relative;\n display: flex;\n flex-wrap: wrap;\n justify-content: flex-start;\n}\n.amap_markers_pop_window::before{\n content: ' ';\n display: block;\n position: absolute;\n bottom: -12px;\n left: 50%;\n margin-left: -7px;\n width: 0;\n height: 0;\n border-top: 12px solid #ddd;\n border-left: 7px solid transparent;\n border-right: 7px solid transparent;\n}\n.amap_markers_pop_window::after{\n content: ' ';\n display: block;\n position: absolute;\n bottom: -11px;\n left: 50%;\n margin-left: -6px;\n width: 0;\n height: 0;\n border-top: 11px solid #fff;\n border-left: 6px solid transparent;\n border-right: 6px solid transparent;\n}\n.amap_markers_pop_window_item{\n cursor:pointer;\n width: 40px;\n height: 50px;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n}\n.amap_markers_pop_window_item span{\n pointer-events: none;\n}\n.amap_markers_window_overflow_warning{\n text-align: center;\n width: 100%;\n margin: 5px 0;\n color: #666;\n}",y.appendChild(m)}var b=s.default.Component,_=25.6,w=46*.8-2,g=46*.8,k=66*.8-2,C={useCluster:!1,markersCache:[],markerIDCache:[]},M=["gridSize","minClusterSize","maxZoom","averageCenter","styles","zoomOnClick","renderCluserMarker"],E=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return"undefined"!=typeof window&&(e.__map__?(n.map=e.__map__,n.element=n.map.getContainer(),n.markersCache=C.markersCache,n.useCluster=null,n.markerIDCache=C.markerIDCache,n.resetOffset=new window.AMap.Pixel(-_/2,-w),n.hoverOffset=new window.AMap.Pixel(-g/2,-k),n.createMarkers(e)):h.default.warning("MAP_INSTANCE_REQUIRED")),n}return a(t,e),u(t,[{key:"shouldComponentUpdate",value:function(){return!1}},{key:"createMarkers",value:function(e){var t=this,n=e.markers||[],r=[],o={};n.length&&n.forEach(function(n,i){var a=t.buildCreateOptions(e,n,i);a.map=t.map;var u=null;if((0,p.default)(e.render)){var l=e.render(n);if(!1!==l){var s=document.createElement("div");s.setAttribute("__react_amap__","1"),u=s,o[i]=l}}if(!u){u=document.createElement("div");var c=document.createElement("img");c.src="//webapi.amap.com/theme/v1.3/markers/n/mark_bs.png",u.appendChild(c)}a.content=u;var f=new window.AMap.Marker(a);f.on("click",function(e){t.onMarkerClick(e)}),f.on("mouseover",function(e){t.onMarkerHover(e)}),f.on("mouseout",function(e){t.onMarkerHoverOut(e)}),f.render=function(e){return function(t){return(0,v.renderMarkerComponent)(t,e)}}(f),t.bindMarkerEvents(f),r.push(f)}),this.markersCache=r,this.markerReactChildDOM=o,this.exposeMarkerInstance(),this.checkClusterSettings(e)}},{key:"checkClusterSettings",value:function(e){var t=this;if(e.useCluster)this.loadClusterPlugin(e.useCluster).then(function(e){e.setMarkers(t.markersCache)});else if(this.mapCluster){var n=this.mapCluster.getMarkers();this.mapCluster.clearMarkers(),n.forEach(function(e){e.setMap(t.map)})}}},{key:"componentDidMount",value:function(){this.map&&this.setMarkerChild()}},{key:"setMarkerChild",value:function(){var e=this;Object.keys(this.markerReactChildDOM).forEach(function(t){var n=e.markersCache[t].getContent(),r=e.markerReactChildDOM[t];e.renderMarkerChild(n,r)})}},{key:"renderMarkerChild",value:function(e,t){(0,c.render)(s.default.createElement("div",null,t),e)}},{key:"buildCreateOptions",value:function(e,t,n){var r={},o=["extData"];return v.MarkerAllProps.forEach(function(i){if(i in t&&-1===o.indexOf(i))r[i]=(0,v.getPropValue)(i,t[i]);else if(i in e)if((0,p.default)(e[i])){var a=e[i].call(null,t,n);r[i]=(0,v.getPropValue)(i,a)}else r[i]=(0,v.getPropValue)(i,e[i])}),r.extData=t,r}},{key:"componentWillReceiveProps",value:function(e){this.map&&this.refreshMarkersLayout(e)}},{key:"refreshMarkersLayout",value:function(e){var t=e.markers!==this.props.markers,n=!!this.props.useCluster!=!!e.useCluster;t&&(this.markersCache.length&&this.markersCache.forEach(function(e){e&&(e.setMap(null),e=null)}),this.markersCache=C.markersCache,this.createMarkers(e),this.setMarkerChild()),(t||n)&&this.markersWindow&&this.markersWindow.close(),n&&this.checkClusterSettings(e)}},{key:"loadClusterPlugin",value:function(e){var t=this;if(this.mapCluster)return Promise.resolve(this.mapCluster);var n="boolean"==typeof e?{}:e;return new Promise(function(e){t.map.plugin(["AMap.MarkerClusterer"],function(){e(t.createClusterPlugin(n))})})}},{key:"createClusterPlugin",value:function(e){var t={},n={minClusterSize:2,zoomOnClick:!1,maxZoom:18,gridSize:60,averageCenter:!0};M.forEach(function(r){t[r]=r in e?e[r]:n[r]}),this.mapCluster=new window.AMap.MarkerClusterer(this.map,[],t);var r={};return"events"in e&&"created"in(r=e.events)&&r.created(this.mapCluster),this.initClusterMarkerWindow(),this.bindClusterEvent(r),this.mapCluster}},{key:"onMarkerClick",value:function(e){var t=e.target;this.triggerMarkerClick(e,t)}},{key:"onMarkerHover",value:function(e){e.target.setTop(!0),this.setMarkerHovered(e,e.target)}},{key:"onMarkerHoverOut",value:function(e){e.target.setTop(!1),this.setMarkerHoverOut(e,e.target)}},{key:"onWindowMarkerClick",value:function(e){var t=e.markerRef;this.triggerMarkerClick(null,t)}},{key:"onWindowMarkerHover",value:function(e){var t=e.markerRef;this.setMarkerHovered(null,t)}},{key:"onWindowMarkerHoverOut",value:function(e){var t=e.markerRef;this.setMarkerHoverOut(null,t)}},{key:"setMarkerHovered",value:function(e,t){this.triggerMarkerHover(e,t)}},{key:"setMarkerHoverOut",value:function(e,t){this.triggerMarkerHoverOut(e,t)}},{key:"triggerMarkerClick",value:function(e,t){var n=this.props.events||{};(0,p.default)(n.click)&&n.click(e,t)}},{key:"triggerMarkerHover",value:function(e,t){var n=this.props.events||{};(0,p.default)(n.mouseover)&&n.mouseover(e,t)}},{key:"triggerMarkerHoverOut",value:function(e,t){var n=this.props.events||{};(0,p.default)(n.mouseout)&&n.mouseout(e,t)}},{key:"initClusterMarkerWindow",value:function(){this.markersWindow=new window.AMap.InfoWindow({isCustom:!0,autoMove:!0,closeWhenClickMap:!0,content:"<span>loading...</span>",showShadow:!1,offset:new window.AMap.Pixel(0,-20)}),this.markersDOM=document.createElement("div"),this.markersDOM.className="amap_markers_pop_window",this.markersWindow.setContent(this.markersDOM)}},{key:"bindClusterEvent",value:function(e){var t=this;this.mapCluster.on("click",function(n){if(t.props.useCluster&&t.props.useCluster.zoomOnClick);else{var r=!0;(0,p.default)(e.click)&&(r=e.click(n)),!1!==r&&t.showMarkersInfoWindow(n)}})}},{key:"showMarkersInfoWindow",value:function(e){var t=this,n=e.lnglat,r=e.markers;if(this.markersDOM.innerHTML="",r&&r.length){var o=r.length;if(o>42&&(r=r.slice(0,42)),r.forEach(function(e){var n=e.getContent(),r=document.createElement("div");r.className="window_marker_item",r.appendChild(n),r.markerRef=e,r.addEventListener("click",t.onWindowMarkerClick.bind(t,r),!0),r.addEventListener("mouseover",t.onWindowMarkerHover.bind(t,r),!0),r.addEventListener("mouseout",t.onWindowMarkerHoverOut.bind(t,r),!0),t.markersDOM.appendChild(r)}),o>42){var i=document.createElement("div");i.className="amap_markers_window_overflow_warning",i.innerText="更多坐标请放大地图查看",this.markersDOM.appendChild(i)}}this.markersWindow.open(this.map,n)}},{key:"exposeMarkerInstance",value:function(){if("events"in this.props){var e=this.props.events||{};(0,p.default)(e.created)&&e.created(this.markersCache)}}},{key:"bindMarkerEvents",value:function(e){var t=this.props.events||{},n=Object.keys(t),r=["click","mouseover","mouseout","created"];n.length&&n.forEach(function(n){-1===r.indexOf(n)&&e.on(n,t[n])})}},{key:"render",value:function(){return null}}]),t}(b);t.default=E},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=n(0),s=r(l),c=n(2),f=r(c),p=n(1),d=r(p),h=n(3),v=["center","radius","draggable","extData","visible","style"],y=v.concat(["zIndex","bubble"]),m=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));if("undefined"!=typeof window)if(e.__map__){var r=n;n.setterMap={visible:function(e){r.mapCircle&&(e?r.mapCircle.show():r.mapCircle.hide())},style:function(e){r.mapCircle&&r.mapCircle.setOptions(e)}},n.converterMap={center:h.toLnglat},n.state={loaded:!1},n.map=e.__map__,n.element=n.map.getContainer(),n.createInstance(e).then(function(){n.setState({loaded:!0}),n.props.onInstanceCreated&&n.props.onInstanceCreated()})}else d.default.warning("MAP_INSTANCE_REQUIRED");return n}return a(t,e),u(t,[{key:"createInstance",value:function(e){var t=this.buildCreateOptions(e);return t.map=this.map,this.mapCircle=new window.AMap.Circle(t),Promise.resolve(this.mapCircle)}},{key:"buildCreateOptions",value:function(e){var t=this,n={};return y.forEach(function(r){if(r in e)if("style"===r&&void 0!==e.style){var o=Object.keys(e.style);o.forEach(function(t){n[t]=e.style[t]})}else n[r]=t.getSetterValue(r,e)}),n}},{key:"getSetterValue",value:function(e,t){return e in this.converterMap?this.converterMap[e](t[e]):t[e]}},{key:"renderEditor",value:function(e){return e?1!==s.default.Children.count(e)?null:s.default.cloneElement(s.default.Children.only(e),{__circle__:this.mapCircle,__map__:this.map,__ele__:this.element}):null}},{key:"render",value:function(){return this.state.loaded?this.renderEditor(this.props.children):null}},{key:"instance",get:function(){return this.mapCircle}}]),t}(s.default.Component);t.default=(0,f.default)(m)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=n(0),s=r(l),c=n(2),f=r(c),p=n(1),d=r(p),h=n(6),v=r(h),y=n(3),m=["path","draggable","extData","style","visible"],b=m.concat(["zIndex","bubble"]),_=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));if("undefined"!=typeof window)if(e.__map__){var r=n;n.setterMap={visible:function(e){e?r.polygon&&r.polygon.show():r.polygon&&r.polygon.hide()},style:function(e){r.polygon.setOptions(e)}},n.converterMap={path:function(e){return r.buildPathValue(e)}},n.state={loaded:!1},n.map=e.__map__,n.element=n.map.getContainer(),setTimeout(function(){n.initMapPolygon(e)},13)}else d.default.warning("MAP_INSTANCE_REQUIRED");return n}return a(t,e),u(t,[{key:"initMapPolygon",value:function(e){var t=this.buildCreateOptions(e);t.map=this.map,this.polygon=new window.AMap.Polygon(t),this.setState({loaded:!0}),this.props.onInstanceCreated&&this.props.onInstanceCreated()}},{key:"buildCreateOptions",value:function(e){var t=this,n={};return b.forEach(function(r){if(r in e)if("style"===r&&e.style){var o=Object.keys(e.style);o.forEach(function(t){n[t]=e.style[t]})}else"visible"!==r&&(n[r]=t.getSetterValue(r,e[r]))}),n}},{key:"detectPropChanged",value:function(e,t){return this.props[e]!==t[e]}},{key:"getSetterValue",value:function(e,t){return e in this.converterMap?this.converterMap[e](t):t}},{key:"buildPathValue",value:function(e){var t=this;if(e.length){var n=e[0];if("number"==typeof n[0])return e.map(function(e){return(0,y.toLnglat)(e)});if("getLng"in n)return e;if("longitude"in n||"lng"in n)return e.map(function(e){return(0,y.toLnglat)(e)});if("length"in n&&n.length)return e.map(function(e){return t.buildPathValue(e)})}return[]}},{key:"renderEditor",value:function(e){if(!e)return null;if(1!==s.default.Children.count(e))return null;var t=s.default.Children.only(e);return t.type===v.default?s.default.cloneElement(t,{__poly__:this.polygon,__map__:this.map}):null}},{key:"render",value:function(){return this.state.loaded?this.renderEditor(this.props.children):null}},{key:"instance",get:function(){return this.polygon}}]),t}(l.Component);t.default=(0,f.default)(_)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=n(0),s=r(l),c=n(2),f=r(c),p=n(1),d=r(p),h=n(6),v=r(h),y=n(3),m=s.default.Component,b=["path","extData","draggable","visible","style"],_=b.concat(["zIndex","bubble","showDir"]),w=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));if("undefined"!=typeof window)if(e.__map__){var r=n;n.setterMap={visible:function(e){e?r.polyline&&r.polyline.show():r.polyline&&r.polyline.hide()},style:function(e){r.polyline.setOptions(e)}},n.converterMap={path:function(e){return r.buildPathValue(e)}},n.state={loaded:!1},n.map=e.__map__,n.element=n.map.getContainer(),setTimeout(function(){n.createMapPolyline(e)},13)}else d.default.warning("MAP_INSTANCE_REQUIRED");return n}return a(t,e),u(t,[{key:"createMapPolyline",value:function(e){var t=this.buildCreateOptions(e);t.map=this.map,this.polyline=new window.AMap.Polyline(t),this.setState({loaded:!0}),this.props.onInstanceCreated&&this.props.onInstanceCreated()}},{key:"buildCreateOptions",value:function(e){var t=this,n={};return _.forEach(function(r){if(r in e)if("style"===r&&e.style){var o=Object.keys(e.style);o.forEach(function(t){n[t]=e.style[t]})}else"visible"!==r&&(n[r]=t.getSetterValue(r,e[r]))}),n}},{key:"detectPropChanged",value:function(e,t){return this.props[e]!==t[e]}},{key:"getSetterValue",value:function(e,t){return e in this.converterMap?this.converterMap[e](t):t}},{key:"buildPathValue",value:function(e){return e.length?"getLng"in e[0]?e:e.map(function(e){return(0,y.toLnglat)(e)}):e}},{key:"renderEditor",value:function(e){if(!e)return null;if(1!==s.default.Children.count(e))return null;var t=s.default.Children.only(e);return t.type===v.default?s.default.cloneElement(t,{__poly__:this.polyline,__map__:this.map}):null}},{key:"render",value:function(){return this.state.loaded?this.renderEditor(this.props.children):null}},{key:"instance",get:function(){return this.polyline}}]),t}(m);t.default=(0,f.default)(w)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=n(0),s=r(l),c=n(5),f=n(2),p=r(f),d=n(1),h=r(d),v=n(3),y=s.default.Component,m=["content","position","size","visible","offset"],b=m.concat(["isCustom","autoMove","closeWhenClickMap","showShadow"]),_=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));if("undefined"!=typeof window)if(e.__map__){var r=n;n.setterMap={visible:function(e){e?(r.showWindow(),r.setClassName(r.props),r.setChild(r.props)):r.closeWindow()}},n.converterMap={size:v.toSize,offset:v.toPixel,position:v.toLnglat},n.map=e.__map__,n.isCustom=!0,setTimeout(function(){n.createInfoWindow(e)},13)}else h.default.warning("MAP_INSTANCE_REQUIRED");return n}return a(t,e),u(t,[{key:"shouldComponentUpdate",value:function(){return!1}},{key:"componentWillReceiveProps",value:function(e){this.map&&this.refreshWindowLayout(e)}},{key:"createInfoWindow",value:function(e){var t=this.buildCreateOptions(e);this.infoWindow=new window.AMap.InfoWindow(t),this.props.onInstanceCreated&&this.props.onInstanceCreated()}},{key:"refreshWindowLayout",value:function(e){this.setChild(e),this.setClassName(e)}},{key:"checkPropChanged",value:function(e,t){return this.props[e]!==t[e]}},{key:"showWindow",value:function(){this.infoWindow.open(this.map,this.infoWindow.getPosition())}},{key:"closeWindow",value:function(){this.infoWindow.close()}},{key:"buildCreateOptions",value:function(e){var t=this,n={};return n.isCustom="isCustom"in e&&!!e.isCustom,"content"in e?n.content=e.content:(this.infoDOM=document.createElement("div"),n.content=this.infoDOM),b.forEach(function(r){r in e&&-1===["visible","isCustom","content"].indexOf(r)&&(n[r]=t.getSetterValue(r,e[r]))}),n}},{key:"getSetterValue",value:function(e,t){return e in this.converterMap?this.converterMap[e](t):t}},{key:"setChild",value:function(e){var t=e.children;this.infoDOM&&t?(0,c.render)(s.default.createElement("div",null,t),this.infoDOM):e.children&&console.warn("因为你设置 isCustom 为 true,InfoWindow 的 Children 被忽略")}},{key:"setClassName",value:function(e){if(this.infoDOM){var t="";"className"in e&&e.className?t+=e.className:!0===e.isCustom&&(t+="amap_markers_pop_window"),this.infoDOM.className=t}}},{key:"render",value:function(){return null}},{key:"instance",get:function(){return this.infoWindow}}]),t}(y);t.default=(0,p.default)(_)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=n(0),s=r(l),c=n(2),f=r(c),p=n(1),d=r(p),h={clickable:!1,opacity:1,visible:!0},v=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));if("undefined"!=typeof window)if(e.__map__){var r=n;n.setterMap={visible:function(e){e?r.image&&r.image.show():r.image&&r.image.hide()},src:function(e){r.image.setImageUrl(e)}},n.converterMap={bounds:function(e){return r.buildBounds(e)}},n.map=e.__map__,n.element=n.map.getContainer(),setTimeout(function(){n.createGroundImage(e)},13)}else d.default.warning("MAP_INSTANCE_REQUIRED");return n}return a(t,e),u(t,[{key:"shouldComponentUpdate",value:function(){return!1}},{key:"checkPropsChanged",value:function(e,t){return this.props[t]!==e[t]}},{key:"createGroundImage",value:function(e){var t=void 0,n=void 0,r=void 0,o=void 0;"src"in e?t=e.src:d.default.warning("SRC_REQUIRED",!0),"bounds"in e?n=this.buildBounds(e.bounds):d.default.warning("BOUNDS_REQUIRED",!0),o="clickable"in e?e.clickable:h.clickable,r="opacity"in e?e.opacity:h.opacity,this.image=new window.AMap.GroundImage(t,n,{map:this.map,clickable:o,opacity:r}),this.props.onInstanceCreated&&this.props.onInstanceCreated()}},{key:"buildBounds",value:function(e){return e?"getSouthWest"in e?e:new window.AMap.Bounds(new window.AMap.LngLat(e.sw.longitude,e.sw.latitude),new window.AMap.LngLat(e.ne.longitude,e.ne.latitude)):e}},{key:"render",value:function(){return null}},{key:"instance",get:function(){return this.image}}]),t}(s.default.Component);t.default=(0,f.default)(v)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=n(0),s=r(l),c=n(1),f=r(c),p=n(4),d=r(p),h=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return"undefined"!=typeof window&&(e.__map__&&e.__circle__?(n.map=e.__map__,n.element=n.map.getContainer(),n.circle=e.__circle__,n.editorActive=!1,n.onPropsUpdate(e)):f.default.warning("CIRCLE_INSTANCE_REQUIRED")),n}return a(t,e),u(t,[{key:"componentWillReceiveProps",value:function(e){this.map&&this.onPropsUpdate(e)}},{key:"onPropsUpdate",value:function(e){"active"in e&&!1===e.active?this.toggleActive(!1,e):this.toggleActive(!0,e)}},{key:"toggleActive",value:function(e,t){e?this.editorActive||this.activeEditor(t):this.editorActive&&this.inactiveEditor()}},{key:"activeEditor",value:function(e){var t=this;this.loadCircleEditor(e).then(function(e){t.editorActive=!0,e.open()})}},{key:"inactiveEditor",value:function(){this.editorActive=!1,this.circleEditor&&this.circleEditor.close()}},{key:"loadCircleEditor",value:function(e){var t=this;return this.circleEditor?Promise.resolve(this.circleEditor):new Promise(function(n){t.map.plugin(["AMap.CircleEditor"],function(){n(t.createEditorInstance(e))})})}},{key:"createEditorInstance",value:function(e){this.circleEditor=new window.AMap.CircleEditor(this.map,this.circle);var t=this.exposeEditorInstance(e);return t&&this.bindEditorEvents(t),this.circleEditor}},{key:"exposeEditorInstance",value:function(e){if("events"in e){var t=e.events||{};return(0,d.default)(t.created)&&t.created(this.circleEditor),delete t.created,t}return!1}},{key:"bindEditorEvents",value:function(e){var t=this,n=Object.keys(e);n.length&&n.forEach(function(n){t.circleEditor.on(n,e[n])})}},{key:"render",value:function(){return null}}]),t}(s.default.Component);t.default=h},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=n(0),s=r(l),c=n(2),f=r(c),p=n(1),d=r(p),h=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return"undefined"!=typeof window&&(e.__map__?(n.map=e.__map__,n.loadToolInstance().then(function(){n.props.onInstanceCreated&&n.props.onInstanceCreated()})):d.default.warning("MAP_INSTANCE_REQUIRED")),n}return a(t,e),u(t,[{key:"shouldComponentUpdate",value:function(){return!1}},{key:"loadToolInstance",value:function(){var e=this;return new Promise(function(t){e.map.plugin(["AMap.MouseTool"],function(){e.tool=new window.AMap.MouseTool(e.map),t()})})}},{key:"render",value:function(){return null}},{key:"instance",get:function(){return this.tool}}]),t}(s.default.Component);t.default=(0,f.default)(h)}])});
\ No newline at end of file
/* eslint-disable */
import React from 'react';
declare type AMapLngLat = {
getLng: Function,
getLat: Function,
};
declare type PureLngLat = {
longitude: number,
latitude: number,
};
declare type LngLat = PureLngLat & AMapLngLat;
declare type AMapSize = {
getWidth: Function,
getHeight: Function,
};
declare type PureSize = {
width: number,
height: number,
};
declare type Size = AMapSize & PureSize;
declare type AMapPixel = {
getX: Function,
getY: Function,
};
declare type PurePixel = [number, number];
declare type Pixel = AMapPixel & PurePixel;
declare type MarkerContent = string | HTMLElement;
declare type PolylinePath = Array<PureLngLat> & Array<AMapLngLat>;
declare type PolygonPath = PolylinePath | Array<PolylinePath>;
declare type EventMap = {[evName: string]: Function};
declare type MapLang = 'zh_cn' | 'zh_en' | 'en';
declare type MapFeature = 'bg' | 'point' | 'road' | 'building';
declare type MapProps = {
protocol?: string,
amapkey?: string,
version?: string,
useAMapUI?: boolean | Function,
onInstanceCreated?: Function,
children: React.Node,
events?: EventMap,
plugins?: Object,
loading: React.Node,
center?: LngLat,
zoom?: number,
zooms?: [number, number],
animateEnable?: boolean,
doubleClickZoom?: boolean,
dragEnable?: boolean,
isHotspot?: boolean,
jogEnable?: boolean,
keyboardEnable?: boolean,
resizeEnable?: boolean,
rotateEnable?: boolean,
scrollWheel?: boolean,
touchZoom?: boolean,
zoomEnable?: boolean,
showIndoorMap?: boolean,
expandZoomRange?: boolean,
viewMode?: '2D' | '3D',
features?: Array<MapFeature>,
pitch?: number,
mapStyle?: string,
labelzIndex?: number,
skyColor?: string,
buildingAnimation?: boolean,
pitchEnable?: boolean,
showBuildingBlock?: boolean,
indoorMap?: any,
cursor?: string,
layers?: Array<any>,
view?: any,
city?: string,
bounds?: any,
limitBounds?: any,
status?: any,
rotation?: number
// lang?: MapLang,
}
declare type MarkerProps = {
position?: LngLat,
offset?: Pixel,
onInstanceCreated?: Function,
icon?: any,
content?: MarkerContent,
className?: string,
draggable?: boolean,
visible?: boolean,
cursor?: string,
zIndex?: number,
angle?: number,
animation?: string,
markers?: Array<Object>,
shadow?: Object,
title?: string,
clickable?: boolean,
extData?: any,
label?: Object,
topWhenClick?: boolean,
bubble?: boolean,
raiseOnDrag?: boolean,
autoRotation?: boolean,
shape?: Object,
events?: Object,
render?: Function,
children?: any,
useCluster?: Object | boolean,
__map__: Object,
__ele__: HTMLDivElement,
};
declare type MapEvent = {
lnglat: AMapLngLat,
target: Object,
markers?: Array<Object>
};
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _withPropsReactive = require('../utils/withPropsReactive');
var _withPropsReactive2 = _interopRequireDefault(_withPropsReactive);
var _log = require('../utils/log');
var _log2 = _interopRequireDefault(_log);
var _common = require('../utils/common');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/*
* props
* {
* __map__ 父级组件传过来的地图实例
* }
*/
var configurableProps = ['center', 'radius', 'draggable', 'extData',
/* 原生的接口中并没有这些对象,这是本组件的扩展 */
'visible', 'style'];
var allProps = configurableProps.concat(['zIndex', 'bubble']);
var Circle = function (_React$Component) {
_inherits(Circle, _React$Component);
function Circle(props) {
_classCallCheck(this, Circle);
var _this = _possibleConstructorReturn(this, (Circle.__proto__ || Object.getPrototypeOf(Circle)).call(this, props));
if (typeof window !== 'undefined') {
if (!props.__map__) {
_log2.default.warning('MAP_INSTANCE_REQUIRED');
} else {
var self = _this;
_this.setterMap = {
visible: function visible(val) {
if (self.mapCircle) {
if (val) {
self.mapCircle.show();
} else {
self.mapCircle.hide();
}
}
},
style: function style(val) {
self.mapCircle && self.mapCircle.setOptions(val);
}
};
_this.converterMap = {
center: _common.toLnglat
};
_this.state = {
loaded: false
};
_this.map = props.__map__;
_this.element = _this.map.getContainer();
_this.createInstance(props).then(function () {
_this.setState({
loaded: true
});
_this.props.onInstanceCreated && _this.props.onInstanceCreated();
});
}
}
return _this;
}
_createClass(Circle, [{
key: 'createInstance',
value: function createInstance(props) {
var options = this.buildCreateOptions(props);
options.map = this.map;
this.mapCircle = new window.AMap.Circle(options);
return Promise.resolve(this.mapCircle);
}
}, {
key: 'buildCreateOptions',
value: function buildCreateOptions(props) {
var _this2 = this;
var options = {};
allProps.forEach(function (key) {
if (key in props) {
if (key === 'style' && props.style !== undefined) {
var styleItem = Object.keys(props.style);
styleItem.forEach(function (item) {
// $FlowFixMe
options[item] = props.style[item];
});
} else {
options[key] = _this2.getSetterValue(key, props);
}
}
});
return options;
}
}, {
key: 'getSetterValue',
value: function getSetterValue(key, props) {
if (key in this.converterMap) {
return this.converterMap[key](props[key]);
}
return props[key];
}
}, {
key: 'renderEditor',
value: function renderEditor(children) {
if (!children) {
return null;
}
if (_react2.default.Children.count(children) !== 1) {
return null;
}
return _react2.default.cloneElement(_react2.default.Children.only(children), {
__circle__: this.mapCircle,
__map__: this.map,
__ele__: this.element
});
}
}, {
key: 'render',
value: function render() {
return this.state.loaded ? this.renderEditor(this.props.children) : null;
}
}, {
key: 'instance',
get: function get() {
return this.mapCircle;
}
}]);
return Circle;
}(_react2.default.Component);
exports.default = (0, _withPropsReactive2.default)(Circle);
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _log = require('../utils/log');
var _log2 = _interopRequireDefault(_log);
var _isFun = require('../utils/isFun');
var _isFun2 = _interopRequireDefault(_isFun);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var CircleEditor = function (_React$Component) {
_inherits(CircleEditor, _React$Component);
function CircleEditor(props) {
_classCallCheck(this, CircleEditor);
var _this = _possibleConstructorReturn(this, (CircleEditor.__proto__ || Object.getPrototypeOf(CircleEditor)).call(this, props));
if (typeof window !== 'undefined') {
if (!(props.__map__ && props.__circle__)) {
_log2.default.warning('CIRCLE_INSTANCE_REQUIRED');
} else {
_this.map = props.__map__;
_this.element = _this.map.getContainer();
_this.circle = props.__circle__;
_this.editorActive = false;
_this.onPropsUpdate(props);
}
}
return _this;
}
_createClass(CircleEditor, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (this.map) {
this.onPropsUpdate(nextProps);
}
}
}, {
key: 'onPropsUpdate',
value: function onPropsUpdate(props) {
if ('active' in props && props.active === false) {
this.toggleActive(false, props);
} else {
this.toggleActive(true, props);
}
}
}, {
key: 'toggleActive',
value: function toggleActive(active, props) {
if (active) {
if (!this.editorActive) {
this.activeEditor(props);
}
} else {
if (this.editorActive) {
this.inactiveEditor();
}
}
}
}, {
key: 'activeEditor',
value: function activeEditor(props) {
var _this2 = this;
this.loadCircleEditor(props).then(function (editor) {
_this2.editorActive = true;
editor.open();
});
}
}, {
key: 'inactiveEditor',
value: function inactiveEditor() {
this.editorActive = false;
if (this.circleEditor) {
this.circleEditor.close();
}
}
}, {
key: 'loadCircleEditor',
value: function loadCircleEditor(props) {
var _this3 = this;
if (this.circleEditor) {
return Promise.resolve(this.circleEditor);
}
return new Promise(function (resolve) {
_this3.map.plugin(['AMap.CircleEditor'], function () {
resolve(_this3.createEditorInstance(props));
});
});
}
}, {
key: 'createEditorInstance',
value: function createEditorInstance(props) {
this.circleEditor = new window.AMap.CircleEditor(this.map, this.circle);
var events = this.exposeEditorInstance(props);
events && this.bindEditorEvents(events);
return this.circleEditor;
}
}, {
key: 'exposeEditorInstance',
value: function exposeEditorInstance(props) {
if ('events' in props) {
var _events = props.events || {};
if ((0, _isFun2.default)(_events.created)) {
_events.created(this.circleEditor);
}
delete _events.created;
return _events;
}
return false;
}
}, {
key: 'bindEditorEvents',
value: function bindEditorEvents(events) {
var _this4 = this;
var list = Object.keys(events);
list.length && list.forEach(function (evName) {
_this4.circleEditor.on(evName, events[evName]);
});
}
}, {
key: 'render',
value: function render() {
return null;
}
}]);
return CircleEditor;
}(_react2.default.Component);
exports.default = CircleEditor;
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _withPropsReactive = require('../utils/withPropsReactive');
var _withPropsReactive2 = _interopRequireDefault(_withPropsReactive);
var _log = require('../utils/log');
var _log2 = _interopRequireDefault(_log);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/*
* props
* {
* __map__ 父级组件传过来的地图实例
* }
*/
var defaultOpts = {
clickable: false,
opacity: 1,
visible: true
};
var GroundImage = function (_React$Component) {
_inherits(GroundImage, _React$Component);
function GroundImage(props) {
_classCallCheck(this, GroundImage);
var _this = _possibleConstructorReturn(this, (GroundImage.__proto__ || Object.getPrototypeOf(GroundImage)).call(this, props));
if (typeof window !== 'undefined') {
if (!props.__map__) {
_log2.default.warning('MAP_INSTANCE_REQUIRED');
} else {
var self = _this;
_this.setterMap = {
visible: function visible(val) {
if (val) {
self.image && self.image.show();
} else {
self.image && self.image.hide();
}
},
src: function src(val) {
self.image.setImageUrl(val);
}
};
_this.converterMap = {
bounds: function bounds(val) {
return self.buildBounds(val);
}
};
_this.map = props.__map__;
_this.element = _this.map.getContainer();
setTimeout(function () {
_this.createGroundImage(props);
}, 13);
}
}
return _this;
}
_createClass(GroundImage, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate() {
return false;
}
}, {
key: 'checkPropsChanged',
value: function checkPropsChanged(nextProps, key) {
return this.props[key] !== nextProps[key];
}
}, {
key: 'createGroundImage',
value: function createGroundImage(props) {
var src = void 0,
bounds = void 0,
opacity = void 0,
clickable = void 0;
if ('src' in props) {
src = props.src;
} else {
_log2.default.warning('SRC_REQUIRED', true);
}
if ('bounds' in props) {
bounds = this.buildBounds(props.bounds);
} else {
_log2.default.warning('BOUNDS_REQUIRED', true);
}
if ('clickable' in props) {
clickable = props.clickable;
} else {
clickable = defaultOpts.clickable;
}
if ('opacity' in props) {
opacity = props.opacity;
} else {
opacity = defaultOpts.opacity;
}
this.image = new window.AMap.GroundImage(src, bounds, {
map: this.map,
clickable: clickable,
opacity: opacity
});
this.props.onInstanceCreated && this.props.onInstanceCreated();
}
}, {
key: 'buildBounds',
value: function buildBounds(rawBounds) {
if (!rawBounds) {
return rawBounds;
}
if ('getSouthWest' in rawBounds) {
return rawBounds;
}
var bounds = new window.AMap.Bounds(new window.AMap.LngLat(rawBounds.sw.longitude, rawBounds.sw.latitude), new window.AMap.LngLat(rawBounds.ne.longitude, rawBounds.ne.latitude));
return bounds;
}
}, {
key: 'render',
value: function render() {
return null;
}
}, {
key: 'instance',
get: function get() {
return this.image;
}
}]);
return GroundImage;
}(_react2.default.Component);
exports.default = (0, _withPropsReactive2.default)(GroundImage);
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MouseTool = exports.Marker = exports.GroundImage = exports.InfoWindow = exports.PolyEditor = exports.Polyline = exports.Polygon = exports.CircleEditor = exports.Circle = exports.Markers = exports.Map = undefined;
var _map = require('./map');
var _map2 = _interopRequireDefault(_map);
var _marker = require('./marker');
var _marker2 = _interopRequireDefault(_marker);
var _markers = require('./markers');
var _markers2 = _interopRequireDefault(_markers);
var _circle = require('./circle');
var _circle2 = _interopRequireDefault(_circle);
var _polygon = require('./polygon');
var _polygon2 = _interopRequireDefault(_polygon);
var _polyline = require('./polyline');
var _polyline2 = _interopRequireDefault(_polyline);
var _infowindow = require('./infowindow');
var _infowindow2 = _interopRequireDefault(_infowindow);
var _groundimage = require('./groundimage');
var _groundimage2 = _interopRequireDefault(_groundimage);
var _circleeditor = require('./circleeditor');
var _circleeditor2 = _interopRequireDefault(_circleeditor);
var _polyeditor = require('./polyeditor');
var _polyeditor2 = _interopRequireDefault(_polyeditor);
var _mousetool = require('./mousetool');
var _mousetool2 = _interopRequireDefault(_mousetool);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.Map = _map2.default;
exports.Markers = _markers2.default;
exports.Circle = _circle2.default;
exports.CircleEditor = _circleeditor2.default;
exports.Polygon = _polygon2.default;
exports.Polyline = _polyline2.default;
exports.PolyEditor = _polyeditor2.default;
exports.InfoWindow = _infowindow2.default;
exports.GroundImage = _groundimage2.default;
exports.Marker = _marker2.default;
exports.MouseTool = _mousetool2.default;
exports.default = {
Map: _map2.default,
Markers: _markers2.default,
Circle: _circle2.default,
CircleEditor: _circleeditor2.default,
Polygon: _polygon2.default,
Polyline: _polyline2.default,
PolyEditor: _polyeditor2.default,
InfoWindow: _infowindow2.default,
GroundImage: _groundimage2.default,
Marker: _marker2.default,
MouseTool: _mousetool2.default
};
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _withPropsReactive = require('../utils/withPropsReactive');
var _withPropsReactive2 = _interopRequireDefault(_withPropsReactive);
var _log = require('../utils/log');
var _log2 = _interopRequireDefault(_log);
var _common = require('../utils/common');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/*
* props
* {
* __map__ 父级组件传过来的地图实例
* }
*/
var Component = _react2.default.Component;
var configurableProps = ['content', 'position', 'size',
/* 以下属性是本插件的扩展 */
'visible',
/* 这个 setOffset 方法高德并没有明确在文档中列出来,不确定会不会撤销 */
'offset'];
var allProps = configurableProps.concat(['isCustom', 'autoMove', 'closeWhenClickMap', 'showShadow']);
var InfoWindow = function (_Component) {
_inherits(InfoWindow, _Component);
function InfoWindow(props) {
_classCallCheck(this, InfoWindow);
var _this = _possibleConstructorReturn(this, (InfoWindow.__proto__ || Object.getPrototypeOf(InfoWindow)).call(this, props));
if (typeof window !== 'undefined') {
if (!props.__map__) {
_log2.default.warning('MAP_INSTANCE_REQUIRED');
} else {
var self = _this;
_this.setterMap = {
visible: function visible(val) {
if (val) {
self.showWindow();
self.setClassName(self.props);
self.setChild(self.props);
} else {
self.closeWindow();
}
}
};
_this.converterMap = {
size: _common.toSize,
offset: _common.toPixel,
position: _common.toLnglat
};
_this.map = props.__map__;
_this.isCustom = true;
setTimeout(function () {
_this.createInfoWindow(props);
}, 13);
}
}
return _this;
}
_createClass(InfoWindow, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate() {
return false;
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (this.map) {
this.refreshWindowLayout(nextProps);
}
}
}, {
key: 'createInfoWindow',
value: function createInfoWindow(props) {
var options = this.buildCreateOptions(props);
this.infoWindow = new window.AMap.InfoWindow(options);
this.props.onInstanceCreated && this.props.onInstanceCreated();
}
}, {
key: 'refreshWindowLayout',
value: function refreshWindowLayout(nextProps) {
this.setChild(nextProps);
this.setClassName(nextProps);
}
}, {
key: 'checkPropChanged',
value: function checkPropChanged(key, nextProps) {
return this.props[key] !== nextProps[key];
}
}, {
key: 'showWindow',
value: function showWindow() {
this.infoWindow.open(this.map, this.infoWindow.getPosition());
}
}, {
key: 'closeWindow',
value: function closeWindow() {
this.infoWindow.close();
}
}, {
key: 'buildCreateOptions',
value: function buildCreateOptions(props) {
var _this2 = this;
var options = {};
// 如果开发者没有设置 isCustom 属性,默认设置为 false
if ('isCustom' in props) {
options.isCustom = !!props.isCustom;
} else {
options.isCustom = false;
}
if ('content' in props) {
options.content = props.content;
} else {
this.infoDOM = document.createElement('div');
options.content = this.infoDOM;
}
allProps.forEach(function (key) {
if (key in props) {
if (['visible', 'isCustom', 'content'].indexOf(key) === -1) {
options[key] = _this2.getSetterValue(key, props[key]);
}
}
});
return options;
}
}, {
key: 'getSetterValue',
value: function getSetterValue(key, value) {
if (key in this.converterMap) {
return this.converterMap[key](value);
}
return value;
}
}, {
key: 'setChild',
value: function setChild(props) {
var child = props.children;
if (this.infoDOM && child) {
(0, _reactDom.render)(_react2.default.createElement(
'div',
null,
child
), this.infoDOM);
} else {
if (props.children) {
console.warn('因为你设置 isCustom 为 true,InfoWindow 的 Children 被忽略');
}
}
}
}, {
key: 'setClassName',
value: function setClassName(props) {
if (this.infoDOM) {
var baseClsValue = '';
// 刷新 className
if ('className' in props && props.className) {
baseClsValue += props.className;
} else if (props.isCustom === true) {
baseClsValue += 'amap_markers_pop_window';
}
this.infoDOM.className = baseClsValue;
}
}
}, {
key: 'render',
value: function render() {
return null;
}
}, {
key: 'instance',
get: function get() {
return this.infoWindow;
}
}]);
return InfoWindow;
}(Component);
exports.default = (0, _withPropsReactive2.default)(InfoWindow);
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _APILoader = require('../utils/APILoader');
var _APILoader2 = _interopRequireDefault(_APILoader);
var _isFun = require('../utils/isFun');
var _isFun2 = _interopRequireDefault(_isFun);
var _log = require('../utils/log');
var _log2 = _interopRequireDefault(_log);
var _common = require('../utils/common');
var _withPropsReactive = require('../utils/withPropsReactive');
var _withPropsReactive2 = _interopRequireDefault(_withPropsReactive);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Component = _react2.default.Component;
var Children = _react2.default.Children;
var containerStyle = {
width: '100%',
height: '100%'
};
var wrapperStyle = {
width: '100%',
height: '100%',
position: 'relative'
// Native supported dynamic props by Amap
};var NativeDynamicProps = ['layers', 'zoom', 'center', 'labelzIndex',
// 'lang', native error in JSSDK when 3D viewMode
'mapStyle', 'features', 'cursor', 'pitch'];
/*
* Props below can set by 'setStatus' altogether
*/
var StatusDynamicProps = ['animateEnable', 'doubleClickZoom', 'dragEnable', 'isHotspot', 'jogEnable', 'keyboardEnable', 'resizeEnable', 'rotateEnable', 'scrollWheel', 'touchZoom', 'zoomEnable'];
var StaticProps = ['view', 'zooms', 'showIndoorMap', 'indoorMap', 'expandZoomRange', 'showBuildingBlock', 'viewMode', 'pitchEnable', 'buildingAnimation', 'skyColor'];
var CreateProps = NativeDynamicProps.concat(StatusDynamicProps, StaticProps);
// const reservedPropName = [
// 'amapkey',
// 'version',
// 'useAMapUI',
// 'onInstanceCreated',
// 'events',
// 'loading',
// 'plugins'
// ]
var defaultOpts = {
MapType: {
showRoad: false,
showTraffic: false,
defaultType: 0
},
ToolBar: {
position: 'RB',
noIpLocate: true,
locate: true,
liteStyle: true,
autoPosition: false
},
OverView: {},
ControlBar: {}
};
var BaseMap = function (_Component) {
_inherits(BaseMap, _Component);
function BaseMap(props) {
_classCallCheck(this, BaseMap);
var _this = _possibleConstructorReturn(this, (BaseMap.__proto__ || Object.getPrototypeOf(BaseMap)).call(this, props));
_this.state = {
mapLoaded: false
};
var self = _this;
_this.setterMap = {
zoom: function zoom(val) {
self.map.setZoom(val);
},
cursor: function cursor(val) {
self.map.setDefaultCursor(val);
},
labelzIndex: function labelzIndex(val) {
self.map.setlabelzIndex(val);
}
};
_this.converterMap = {
center: _common.toLnglat
};
if (typeof window !== 'undefined') {
_this.pluginMap = {};
new _APILoader2.default({
key: props.amapkey,
useAMapUI: props.useAMapUI,
version: props.version,
protocol: props.protocol
}).load().then(function () {
_this.createInstance();
if (!_this.state.mapLoaded) {
_this.setState({
mapLoaded: true
});
}
});
}
return _this;
}
_createClass(BaseMap, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (this.state.mapLoaded) {
this.updateMapProps(this.props, nextProps);
}
}
}, {
key: 'renderChildren',
value: function renderChildren() {
var _this2 = this;
return Children.map(this.props.children, function (child) {
if (child) {
var cType = child.type;
/* 针对下面两种组件不注入地图相关属性
* 1. 明确声明不需要注入的
* 2. DOM 元素
*/
if (cType.preventAmap || typeof cType === 'string') {
return child;
}
return _react2.default.cloneElement(child, {
__map__: _this2.map
});
}
return child;
});
}
}, {
key: 'createInstance',
value: function createInstance() {
if (!this.map) {
var options = this.buildCreateOptions();
this.map = new window.AMap.Map(this.mapWrapper, options);
// install map plugins
this.setPlugins(this.props);
this.props.onInstanceCreated && this.props.onInstanceCreated();
}
}
}, {
key: 'buildCreateOptions',
value: function buildCreateOptions() {
var _this3 = this;
var props = this.props;
var options = {};
CreateProps.forEach(function (key) {
if (key in props) {
options[key] = _this3.getSetterValue(key, props);
}
});
return options;
}
}, {
key: 'updateMapProps',
value: function updateMapProps(prevProps, nextProps) {
var _this4 = this;
var nextMapStatus = {};
var statusChangeFlag = false;
var statusPropExist = false;
StatusDynamicProps.forEach(function (key) {
if (key in nextProps) {
statusPropExist = true;
if (_this4.detectPropChanged(key, prevProps, nextProps)) {
statusChangeFlag = true;
nextMapStatus[key] = nextProps[key];
}
}
});
statusChangeFlag && this.map.setStatus(nextMapStatus);
if (statusPropExist && 'status' in nextProps) {
_log2.default.warning('\u4EE5\u4E0B\u8FD9\u4E9B\u5C5E\u6027\u53EF\u4EE5\u5355\u72EC\u63D0\u4F9B\u8FDB\u884C\u914D\u7F6E\uFF0C\u4E5F\u53EF\u4EE5\u7EDF\u4E00\u4F5C\u4E3A\u2018status\u2019\u5C5E\u6027\u914D\u7F6E\uFF1B\u4F46\u662F\u8BF7\u4E0D\u8981\u540C\u65F6\u4F7F\u7528\u8FD9\u4E24\u79CD\u65B9\u5F0F\u3002\n\uFF08' + StatusDynamicProps.join(', ') + '\uFF09');
}
StaticProps.forEach(function (key) {
if (key in nextProps) {
if (_this4.detectPropChanged(key, prevProps, nextProps)) {
_log2.default.warning('\'' + key + '\' \u662F\u4E00\u4E2A\u9759\u6001\u5C5E\u6027\uFF0C\u5730\u56FE\u5B9E\u4F8B\u521B\u5EFA\u6210\u529F\u540E\u65E0\u6CD5\u4FEE\u6539');
}
}
});
this.setPlugins(nextProps);
}
}, {
key: 'getSetterValue',
value: function getSetterValue(key, props) {
if (key in this.converterMap) {
return this.converterMap[key](props[key]);
}
return props[key];
}
}, {
key: 'detectPropChanged',
value: function detectPropChanged(key, prevProps, nextProps) {
return prevProps[key] !== nextProps[key];
}
}, {
key: 'setPlugins',
value: function setPlugins(props) {
var _this5 = this;
var pluginList = ['Scale', 'ToolBar', 'MapType', 'OverView', 'ControlBar'];
if ('plugins' in props) {
var plugins = props.plugins;
if (plugins && plugins.length) {
plugins.forEach(function (p) {
var name = void 0,
config = void 0,
visible = void 0;
if (typeof p === 'string') {
name = p;
config = null;
visible = true;
} else {
name = p.name;
config = p.options || {};
visible = 'visible' in config && typeof config.visible === 'boolean' ? config.visible : true;
delete config.visible;
}
var idx = pluginList.indexOf(name);
if (idx === -1) {
_log2.default.warning('\u6CA1\u6709 \u2018' + name + '\u2019 \u8FD9\u4E2A\u63D2\u4EF6\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u62FC\u5199\u9519\u8BEF');
} else {
if (visible) {
pluginList.splice(idx, 1);
_this5.installPlugin(name, config);
}
}
});
}
}
this.removeOrDisablePlugins(pluginList);
}
}, {
key: 'removeOrDisablePlugins',
value: function removeOrDisablePlugins(plugins) {
var _this6 = this;
if (plugins && plugins.length) {
plugins.forEach(function (p) {
if (p in _this6.pluginMap) {
// ControlBar has no 'hide' method
if (p === 'ControlBar') {
_this6.map.removeControl(_this6.pluginMap[p]);
delete _this6.pluginMap[p];
} else {
_this6.pluginMap[p].hide();
}
}
});
}
}
}, {
key: 'installPlugin',
value: function installPlugin(name, opts) {
opts = opts || {};
switch (name) {
case 'Scale':
case 'ToolBar':
case 'OverView':
case 'MapType':
this.setMapPlugin(name, opts);
break;
case 'ControlBar':
this.setControlBar(opts);
break;
default:
// do nothing
}
}
}, {
key: 'setMapPlugin',
value: function setMapPlugin(name, opts) {
var _this7 = this;
if (this.pluginMap[name]) {
this.pluginMap[name].show();
} else {
var onCreated = opts.onCreated,
restOpts = _objectWithoutProperties(opts, ['onCreated']);
var initOpts = _extends({}, defaultOpts[name], restOpts);
this.map.plugin(['AMap.' + name], function () {
_this7.pluginMap[name] = new window.AMap[name](initOpts);
_this7.map.addControl(_this7.pluginMap[name]);
if ((0, _isFun2.default)(onCreated)) {
onCreated(_this7.pluginMap[name]);
}
});
}
}
}, {
key: 'setControlBar',
value: function setControlBar(opts) {
var _this8 = this;
if (this.pluginMap.ControlBar) {
// do nothing
} else {
var onCreated = opts.onCreated,
restOpts = _objectWithoutProperties(opts, ['onCreated']);
var initOpts = _extends({}, defaultOpts.ControlBar, restOpts);
this.map.plugin(['AMap.ControlBar'], function () {
_this8.pluginMap.ControlBar = new window.AMap.ControlBar(initOpts);
_this8.map.addControl(_this8.pluginMap.ControlBar);
if ((0, _isFun2.default)(onCreated)) {
onCreated(_this8.pluginMap.ControlBar);
}
});
}
}
}, {
key: 'render',
value: function render() {
var _this9 = this;
return _react2.default.createElement(
'div',
{ style: wrapperStyle },
_react2.default.createElement(
'div',
{ ref: function ref(div) {
_this9.mapWrapper = div;
}, style: containerStyle },
this.state.mapLoaded ? null : this.props.loading || null
),
_react2.default.createElement(
'div',
null,
this.state.mapLoaded ? this.renderChildren() : null
)
);
}
}, {
key: 'instance',
get: function get() {
return this.map;
}
}]);
return BaseMap;
}(Component);
exports.default = (0, _withPropsReactive2.default)(BaseMap);
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _log = require('../utils/log');
var _log2 = _interopRequireDefault(_log);
var _withPropsReactive = require('../utils/withPropsReactive');
var _withPropsReactive2 = _interopRequireDefault(_withPropsReactive);
var _markerUtils = require('../utils/markerUtils');
var _common = require('../utils/common');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Marker = function (_React$Component) {
_inherits(Marker, _React$Component);
function Marker(props) {
_classCallCheck(this, Marker);
var _this = _possibleConstructorReturn(this, (Marker.__proto__ || Object.getPrototypeOf(Marker)).call(this, props));
if (typeof window !== 'undefined') {
if (!props.__map__) {
_log2.default.warning('MAP_INSTANCE_REQUIRED');
} else {
var self = _this;
_this.setterMap = {
visible: function visible(val) {
if (val) {
self.marker && self.marker.show();
} else {
self.marker && self.marker.hide();
}
},
zIndex: function zIndex(val) {
self.marker && self.marker.setzIndex(val);
}
};
_this.converterMap = {
position: _common.toLnglat,
offset: _common.toPixel
};
_this.map = props.__map__;
_this.element = _this.map.getContainer();
setTimeout(function () {
_this.createMarker(props);
}, 13);
}
}
return _this;
}
_createClass(Marker, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate() {
return false;
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (this.map) {
this.refreshMarkerLayout(nextProps);
}
}
}, {
key: 'createMarker',
value: function createMarker(props) {
var options = this.buildCreateOptions(props);
this.marker = new window.AMap.Marker(options);
this.marker.render = function (marker) {
return function (component) {
(0, _markerUtils.renderMarkerComponent)(component, marker);
};
}(this.marker);
this.props.onInstanceCreated && this.props.onInstanceCreated();
this.setMarkerLayout(props);
this.setChildComponent(props);
}
// 在创建实例时根据传入配置,设置初始化选项
}, {
key: 'buildCreateOptions',
value: function buildCreateOptions(props) {
var _this2 = this;
var opts = {};
_markerUtils.MarkerAllProps.forEach(function (key) {
if (key in props) {
opts[key] = _this2.getSetterParam(key, props[key]);
}
});
opts.map = this.map;
return opts;
}
// 初始化标记的外观
}, {
key: 'setMarkerLayout',
value: function setMarkerLayout(props) {
if ('render' in props || 'children' in props && props.children) {
this.createContentWrapper();
if ('className' in props && props.className) {
// https://github.com/ElemeFE/react-amap/issues/40
this.contentWrapper.className = props.className;
}
}
}
}, {
key: 'createContentWrapper',
value: function createContentWrapper() {
this.contentWrapper = document.createElement('div');
this.marker.setContent(this.contentWrapper);
}
}, {
key: 'setChildComponent',
value: function setChildComponent(props) {
if (this.contentWrapper) {
if ('className' in props && props.className) {
// https://github.com/ElemeFE/react-amap/issues/40
this.contentWrapper.className = props.className;
}
if ('render' in props) {
(0, _markerUtils.renderMarkerComponent)(props.render, this.marker);
} else if ('children' in props) {
var child = props.children;
var childType = typeof child === 'undefined' ? 'undefined' : _typeof(child);
if (childType !== 'undefined' && this.contentWrapper) {
(0, _reactDom.render)(_react2.default.createElement(
'div',
null,
child
), this.contentWrapper);
}
}
}
}
}, {
key: 'refreshMarkerLayout',
value: function refreshMarkerLayout(nextProps) {
this.setChildComponent(nextProps);
}
}, {
key: 'getSetterParam',
value: function getSetterParam(key, val) {
if (key in this.converterMap) {
return this.converterMap[key](val);
}
return val;
}
}, {
key: 'render',
value: function render() {
return null;
}
}, {
key: 'instance',
get: function get() {
return this.marker;
}
}]);
return Marker;
}(_react2.default.Component);
exports.default = (0, _withPropsReactive2.default)(Marker);
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _isFun = require('../utils/isFun');
var _isFun2 = _interopRequireDefault(_isFun);
var _log = require('../utils/log');
var _log2 = _interopRequireDefault(_log);
var _markerUtils = require('../utils/markerUtils');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
if (typeof window !== 'undefined') {
var styleText = '.amap_markers_pop_window{\n padding: 10px;\n border: 1px solid #ddd;\n border-radius: 8px;\n background: #fff;\n position: relative;\n display: flex;\n flex-wrap: wrap;\n justify-content: flex-start;\n}\n.amap_markers_pop_window::before{\n content: \' \';\n display: block;\n position: absolute;\n bottom: -12px;\n left: 50%;\n margin-left: -7px;\n width: 0;\n height: 0;\n border-top: 12px solid #ddd;\n border-left: 7px solid transparent;\n border-right: 7px solid transparent;\n}\n.amap_markers_pop_window::after{\n content: \' \';\n display: block;\n position: absolute;\n bottom: -11px;\n left: 50%;\n margin-left: -6px;\n width: 0;\n height: 0;\n border-top: 11px solid #fff;\n border-left: 6px solid transparent;\n border-right: 6px solid transparent;\n}\n.amap_markers_pop_window_item{\n cursor:pointer;\n width: 40px;\n height: 50px;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n}\n.amap_markers_pop_window_item span{\n pointer-events: none;\n}\n.amap_markers_window_overflow_warning{\n text-align: center;\n width: 100%;\n margin: 5px 0;\n color: #666;\n}';
var headEl = document.head || document.getElementsByTagName('head')[0];
var styleEl = document.createElement('style');
styleEl.type = 'text/css';
styleEl.textContent = styleText;
headEl.appendChild(styleEl);
}
var Component = _react2.default.Component;
var SCALE = 0.8;
var SIZE_WIDTH = 32 * SCALE;
var SIZE_HEIGHT = 46 * SCALE - 2;
var SIZE_HOVER_WIDTH = 46 * SCALE;
var SIZE_HOVER_HEIGHT = 66 * SCALE - 2;
var MAX_INFO_MARKERS = 42;
var defaultOpts = {
useCluster: false,
markersCache: [],
markerIDCache: []
};
var ClusterProps = ['gridSize', 'minClusterSize', 'maxZoom', 'averageCenter', 'styles', 'zoomOnClick', 'renderCluserMarker'];
var IdKey = '__react_amap__';
/*
* props
* {
* useCluster(boolean)是否使用聚合点
* markers(array<>)坐标列表
* __map__ 父级组件传过来的地图实例
* __ele__ 父级组件传过来的地图容器
* }
*/
var Markers = function (_Component) {
_inherits(Markers, _Component);
function Markers(props) {
_classCallCheck(this, Markers);
var _this = _possibleConstructorReturn(this, (Markers.__proto__ || Object.getPrototypeOf(Markers)).call(this, props));
if (typeof window !== 'undefined') {
if (!props.__map__) {
_log2.default.warning('MAP_INSTANCE_REQUIRED');
} else {
_this.map = props.__map__;
_this.element = _this.map.getContainer();
_this.markersCache = defaultOpts.markersCache;
_this.useCluster = null;
_this.markerIDCache = defaultOpts.markerIDCache;
_this.resetOffset = new window.AMap.Pixel(-SIZE_WIDTH / 2, -SIZE_HEIGHT);
_this.hoverOffset = new window.AMap.Pixel(-SIZE_HOVER_WIDTH / 2, -SIZE_HOVER_HEIGHT);
_this.createMarkers(props);
}
}
return _this;
}
_createClass(Markers, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate() {
return false;
}
}, {
key: 'createMarkers',
value: function createMarkers(props) {
var _this2 = this;
var markers = props.markers || [];
var mapMarkers = [];
var markerReactChildDOM = {};
markers.length && markers.forEach(function (raw, idx) {
var options = _this2.buildCreateOptions(props, raw, idx);
options.map = _this2.map;
var markerContent = null;
if ((0, _isFun2.default)(props.render)) {
// $FlowFixMe
var markerChild = props.render(raw);
if (markerChild !== false) {
var div = document.createElement('div');
div.setAttribute(IdKey, '1');
markerContent = div;
markerReactChildDOM[idx] = markerChild;
}
}
if (!markerContent) {
markerContent = document.createElement('div');
var img = document.createElement('img');
img.src = '//webapi.amap.com/theme/v1.3/markers/n/mark_bs.png';
markerContent.appendChild(img);
}
options.content = markerContent;
var marker = new window.AMap.Marker(options);
marker.on('click', function (e) {
_this2.onMarkerClick(e);
});
marker.on('mouseover', function (e) {
_this2.onMarkerHover(e);
});
marker.on('mouseout', function (e) {
_this2.onMarkerHoverOut(e);
});
marker.render = function (marker) {
return function (component) {
return (0, _markerUtils.renderMarkerComponent)(component, marker);
};
}(marker);
_this2.bindMarkerEvents(marker);
mapMarkers.push(marker);
});
this.markersCache = mapMarkers;
this.markerReactChildDOM = markerReactChildDOM;
this.exposeMarkerInstance();
this.checkClusterSettings(props);
}
}, {
key: 'checkClusterSettings',
value: function checkClusterSettings(props) {
var _this3 = this;
if (props.useCluster) {
this.loadClusterPlugin(props.useCluster).then(function (cluster) {
cluster.setMarkers(_this3.markersCache);
});
} else {
if (this.mapCluster) {
var markers = this.mapCluster.getMarkers();
this.mapCluster.clearMarkers();
markers.forEach(function (marker) {
marker.setMap(_this3.map);
});
}
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
if (this.map) {
this.setMarkerChild();
}
}
}, {
key: 'setMarkerChild',
value: function setMarkerChild() {
var _this4 = this;
Object.keys(this.markerReactChildDOM).forEach(function (idx) {
var dom = _this4.markersCache[idx].getContent();
var child = _this4.markerReactChildDOM[idx];
_this4.renderMarkerChild(dom, child);
});
}
}, {
key: 'renderMarkerChild',
value: function renderMarkerChild(dom, child) {
(0, _reactDom.render)(_react2.default.createElement(
'div',
null,
child
), dom);
}
}, {
key: 'buildCreateOptions',
value: function buildCreateOptions(props, raw, idx) {
var result = {};
// 强制用户通过 render 函数来定义外观
// const disabledKeys = ['label', 'icon', 'content'];
// 还是不强制好,通过覆盖的方式来(如果有 render,覆盖 content/icon);
var disabledKeys = ['extData'];
_markerUtils.MarkerAllProps.forEach(function (key) {
if (key in raw && disabledKeys.indexOf(key) === -1) {
result[key] = (0, _markerUtils.getPropValue)(key, raw[key]);
} else if (key in props) {
if ((0, _isFun2.default)(props[key])) {
var tmpValue = props[key].call(null, raw, idx);
result[key] = (0, _markerUtils.getPropValue)(key, tmpValue);
} else {
result[key] = (0, _markerUtils.getPropValue)(key, props[key]);
}
}
});
result.extData = raw;
return result;
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (this.map) {
this.refreshMarkersLayout(nextProps);
}
}
}, {
key: 'refreshMarkersLayout',
value: function refreshMarkersLayout(nextProps) {
var markerChanged = nextProps.markers !== this.props.markers;
var clusterChanged = !!this.props.useCluster !== !!nextProps.useCluster;
if (markerChanged) {
this.markersCache.length && this.markersCache.forEach(function (marker) {
if (marker) {
marker.setMap(null);
marker = null;
}
});
this.markersCache = defaultOpts.markersCache;
this.createMarkers(nextProps);
this.setMarkerChild();
}
if (markerChanged || clusterChanged) {
if (this.markersWindow) {
this.markersWindow.close();
}
}
if (clusterChanged) {
this.checkClusterSettings(nextProps);
}
}
}, {
key: 'loadClusterPlugin',
value: function loadClusterPlugin(clusterConfig) {
var _this5 = this;
if (this.mapCluster) {
return Promise.resolve(this.mapCluster);
}
var config = typeof clusterConfig === 'boolean' ? {} : clusterConfig;
return new Promise(function (resolve) {
_this5.map.plugin(['AMap.MarkerClusterer'], function () {
resolve(_this5.createClusterPlugin(config));
});
});
}
}, {
key: 'createClusterPlugin',
value: function createClusterPlugin(config) {
var options = {};
// const style = {
// url: clusterIcon,
// size: new window.AMap.Size(56, 56),
// offset: new window.AMap.Pixel(-28, -28)
// };
var defalutOptions = {
minClusterSize: 2,
zoomOnClick: false,
maxZoom: 18,
gridSize: 60,
// styles: [style, style, style],
averageCenter: true
};
ClusterProps.forEach(function (key) {
if (key in config) {
options[key] = config[key];
} else {
options[key] = defalutOptions[key];
}
});
this.mapCluster = new window.AMap.MarkerClusterer(this.map, [], options);
var events = {};
if ('events' in config) {
events = config.events;
if ('created' in events) {
events.created(this.mapCluster);
}
}
this.initClusterMarkerWindow();
this.bindClusterEvent(events);
return this.mapCluster;
}
}, {
key: 'onMarkerClick',
value: function onMarkerClick(e) {
var marker = e.target;
this.triggerMarkerClick(e, marker);
}
}, {
key: 'onMarkerHover',
value: function onMarkerHover(e) {
e.target.setTop(true);
this.setMarkerHovered(e, e.target);
}
}, {
key: 'onMarkerHoverOut',
value: function onMarkerHoverOut(e) {
e.target.setTop(false);
this.setMarkerHoverOut(e, e.target);
}
}, {
key: 'onWindowMarkerClick',
value: function onWindowMarkerClick(element) {
var marker = element.markerRef;
this.triggerMarkerClick(null, marker);
}
}, {
key: 'onWindowMarkerHover',
value: function onWindowMarkerHover(element) {
var marker = element.markerRef;
this.setMarkerHovered(null, marker);
}
}, {
key: 'onWindowMarkerHoverOut',
value: function onWindowMarkerHoverOut(element) {
var marker = element.markerRef;
this.setMarkerHoverOut(null, marker);
}
}, {
key: 'setMarkerHovered',
value: function setMarkerHovered(e, marker) {
this.triggerMarkerHover(e, marker);
}
}, {
key: 'setMarkerHoverOut',
value: function setMarkerHoverOut(e, marker) {
this.triggerMarkerHoverOut(e, marker);
}
}, {
key: 'triggerMarkerClick',
value: function triggerMarkerClick(e, marker) {
// const raw = marker.getExtData();
var events = this.props.events || {};
if ((0, _isFun2.default)(events.click)) {
events.click(e, marker);
}
}
}, {
key: 'triggerMarkerHover',
value: function triggerMarkerHover(e, marker) {
// const raw = marker.getExtData();
var events = this.props.events || {};
if ((0, _isFun2.default)(events.mouseover)) {
events.mouseover(e, marker);
}
}
}, {
key: 'triggerMarkerHoverOut',
value: function triggerMarkerHoverOut(e, marker) {
// const raw = marker.getExtData();
var events = this.props.events || {};
if ((0, _isFun2.default)(events.mouseout)) {
events.mouseout(e, marker);
}
}
}, {
key: 'initClusterMarkerWindow',
value: function initClusterMarkerWindow() {
this.markersWindow = new window.AMap.InfoWindow({
isCustom: true,
autoMove: true,
closeWhenClickMap: true,
content: '<span>loading...</span>',
showShadow: false,
offset: new window.AMap.Pixel(0, -20)
});
this.markersDOM = document.createElement('div');
this.markersDOM.className = 'amap_markers_pop_window';
this.markersWindow.setContent(this.markersDOM);
}
}, {
key: 'bindClusterEvent',
value: function bindClusterEvent(events) {
var _this6 = this;
this.mapCluster.on('click', function (e) {
if (_this6.props.useCluster && _this6.props.useCluster.zoomOnClick) {
//
} else {
var returnValue = true;
if ((0, _isFun2.default)(events.click)) {
returnValue = events.click(e);
}
if (returnValue !== false) {
_this6.showMarkersInfoWindow(e);
}
}
});
}
}, {
key: 'showMarkersInfoWindow',
value: function showMarkersInfoWindow(e) {
var _this7 = this;
var pos = e.lnglat;
var markers = e.markers;
this.markersDOM.innerHTML = '';
if (markers && markers.length) {
var length = markers.length;
if (length > MAX_INFO_MARKERS) {
markers = markers.slice(0, MAX_INFO_MARKERS);
}
markers.forEach(function (m) {
var contentDOM = m.getContent();
var itemDOM = document.createElement('div');
itemDOM.className = 'window_marker_item';
itemDOM.appendChild(contentDOM);
itemDOM.markerRef = m;
itemDOM.addEventListener('click', _this7.onWindowMarkerClick.bind(_this7, itemDOM), true);
itemDOM.addEventListener('mouseover', _this7.onWindowMarkerHover.bind(_this7, itemDOM), true);
itemDOM.addEventListener('mouseout', _this7.onWindowMarkerHoverOut.bind(_this7, itemDOM), true);
_this7.markersDOM.appendChild(itemDOM);
});
if (length > MAX_INFO_MARKERS) {
var warning = document.createElement('div');
warning.className = 'amap_markers_window_overflow_warning';
warning.innerText = '更多坐标请放大地图查看';
this.markersDOM.appendChild(warning);
}
}
this.markersWindow.open(this.map, pos);
}
}, {
key: 'exposeMarkerInstance',
value: function exposeMarkerInstance() {
if ('events' in this.props) {
var events = this.props.events || {};
if ((0, _isFun2.default)(events.created)) {
events.created(this.markersCache);
}
}
}
}, {
key: 'bindMarkerEvents',
value: function bindMarkerEvents(marker) {
var events = this.props.events || {};
var list = Object.keys(events);
var preserveEv = ['click', 'mouseover', 'mouseout', 'created'];
list.length && list.forEach(function (evName) {
if (preserveEv.indexOf(evName) === -1) {
marker.on(evName, events[evName]);
}
});
}
}, {
key: 'render',
value: function render() {
return null;
}
}]);
return Markers;
}(Component);
exports.default = Markers;
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _withPropsReactive = require('../utils/withPropsReactive');
var _withPropsReactive2 = _interopRequireDefault(_withPropsReactive);
var _log = require('../utils/log');
var _log2 = _interopRequireDefault(_log);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MouseTool = function (_React$Component) {
_inherits(MouseTool, _React$Component);
function MouseTool(props) {
_classCallCheck(this, MouseTool);
var _this = _possibleConstructorReturn(this, (MouseTool.__proto__ || Object.getPrototypeOf(MouseTool)).call(this, props));
if (typeof window !== 'undefined') {
if (!props.__map__) {
_log2.default.warning('MAP_INSTANCE_REQUIRED');
} else {
_this.map = props.__map__;
_this.loadToolInstance().then(function () {
_this.props.onInstanceCreated && _this.props.onInstanceCreated();
});
}
}
return _this;
}
_createClass(MouseTool, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate() {
return false;
}
}, {
key: 'loadToolInstance',
value: function loadToolInstance() {
var _this2 = this;
return new Promise(function (resolve) {
_this2.map.plugin(['AMap.MouseTool'], function () {
_this2.tool = new window.AMap.MouseTool(_this2.map);
resolve();
});
});
}
}, {
key: 'render',
value: function render() {
return null;
}
}, {
key: 'instance',
get: function get() {
return this.tool;
}
}]);
return MouseTool;
}(_react2.default.Component);
exports.default = (0, _withPropsReactive2.default)(MouseTool);
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _withPropsReactive = require('../utils/withPropsReactive');
var _withPropsReactive2 = _interopRequireDefault(_withPropsReactive);
var _log = require('../utils/log');
var _log2 = _interopRequireDefault(_log);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var PolyEditor = function (_React$Component) {
_inherits(PolyEditor, _React$Component);
function PolyEditor(props) {
_classCallCheck(this, PolyEditor);
var _this = _possibleConstructorReturn(this, (PolyEditor.__proto__ || Object.getPrototypeOf(PolyEditor)).call(this, props));
if (typeof window !== 'undefined') {
if (!(props.__map__ && props.__poly__)) {
_log2.default.warning('MAP_INSTANCE_REQUIRED');
} else {
var self = _this;
_this.setterMap = {
active: function active(val) {
self.toggleActive(val);
}
};
_this.map = props.__map__;
_this.poly = props.__poly__;
_this.editorActive = false;
_this.createEditorInstance().then(function () {
_this.props.onInstanceCreated && _this.props.onInstanceCreated();
});
}
}
return _this;
}
_createClass(PolyEditor, [{
key: 'toggleActive',
value: function toggleActive(active) {
if (active) {
if (!this.editorActive) {
this.activeEditor();
}
} else {
if (this.editorActive) {
this.inactiveEditor();
}
}
}
}, {
key: 'activeEditor',
value: function activeEditor() {
if (this.polyEditor) {
this.editorActive = true;
this.polyEditor.open();
}
}
}, {
key: 'inactiveEditor',
value: function inactiveEditor() {
this.editorActive = false;
if (this.polyEditor) {
this.polyEditor.close();
}
}
}, {
key: 'createEditorInstance',
value: function createEditorInstance() {
var _this2 = this;
if (this.polyEditor) {
return Promise.resolve(this.polyEditor);
}
return new Promise(function (resolve) {
_this2.map.plugin(['AMap.PolyEditor'], function () {
_this2.polyEditor = new window.AMap.PolyEditor(_this2.map, _this2.poly);
resolve(_this2.polyEditor);
});
});
}
}, {
key: 'render',
value: function render() {
return null;
}
}, {
key: 'instance',
get: function get() {
return this.polyEditor;
}
}]);
return PolyEditor;
}(_react2.default.Component);
exports.default = (0, _withPropsReactive2.default)(PolyEditor);
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _withPropsReactive = require('../utils/withPropsReactive');
var _withPropsReactive2 = _interopRequireDefault(_withPropsReactive);
var _log = require('../utils/log');
var _log2 = _interopRequireDefault(_log);
var _polyeditor = require('../polyeditor');
var _polyeditor2 = _interopRequireDefault(_polyeditor);
var _common = require('../utils/common');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/*
* props
* {
* __map__ 父级组件传过来的地图实例
*
* }
*/
var configurableProps = ['path', 'draggable', 'extData',
/* 本插件扩展的属性*/
'style', 'visible'];
var allProps = configurableProps.concat(['zIndex', 'bubble']);
var Polygon = function (_Component) {
_inherits(Polygon, _Component);
function Polygon(props) {
_classCallCheck(this, Polygon);
var _this = _possibleConstructorReturn(this, (Polygon.__proto__ || Object.getPrototypeOf(Polygon)).call(this, props));
if (typeof window !== 'undefined') {
if (!props.__map__) {
_log2.default.warning('MAP_INSTANCE_REQUIRED');
} else {
var self = _this;
_this.setterMap = {
visible: function visible(val) {
if (val) {
self.polygon && self.polygon.show();
} else {
self.polygon && self.polygon.hide();
}
},
style: function style(val) {
self.polygon.setOptions(val);
}
};
_this.converterMap = {
path: function path(val) {
return self.buildPathValue(val);
}
};
_this.state = {
loaded: false
};
_this.map = props.__map__;
_this.element = _this.map.getContainer();
setTimeout(function () {
_this.initMapPolygon(props);
}, 13);
}
}
return _this;
}
_createClass(Polygon, [{
key: 'initMapPolygon',
value: function initMapPolygon(props) {
var options = this.buildCreateOptions(props);
options.map = this.map;
this.polygon = new window.AMap.Polygon(options);
this.setState({
loaded: true
});
this.props.onInstanceCreated && this.props.onInstanceCreated();
}
}, {
key: 'buildCreateOptions',
value: function buildCreateOptions(props) {
var _this2 = this;
var options = {};
allProps.forEach(function (key) {
if (key in props) {
if (key === 'style' && props.style) {
var styleItem = Object.keys(props.style);
styleItem.forEach(function (item) {
// $FlowFixMe
options[item] = props.style[item];
});
// visible 做特殊处理
} else if (key !== 'visible') {
options[key] = _this2.getSetterValue(key, props[key]);
}
}
});
return options;
}
}, {
key: 'detectPropChanged',
value: function detectPropChanged(key, nextProps) {
return this.props[key] !== nextProps[key];
}
}, {
key: 'getSetterValue',
value: function getSetterValue(key, value) {
if (key in this.converterMap) {
return this.converterMap[key](value);
}
return value;
}
}, {
key: 'buildPathValue',
value: function buildPathValue(path) {
var _this3 = this;
if (path.length) {
var firstNode = path[0];
if (typeof firstNode[0] === 'number') {
return path.map(function (p) {
return (0, _common.toLnglat)(p);
});
}
if ('getLng' in firstNode) {
return path;
}
if ('longitude' in firstNode || 'lng' in firstNode) {
return path.map(function (p) {
return (0, _common.toLnglat)(p);
});
}
if ('length' in firstNode && firstNode.length) {
// $FlowFixMe
return path.map(function (ring) {
return _this3.buildPathValue(ring);
});
}
}
return [];
}
}, {
key: 'renderEditor',
value: function renderEditor(children) {
if (!children) {
return null;
}
if (_react2.default.Children.count(children) !== 1) {
return null;
}
var child = _react2.default.Children.only(children);
if (child.type === _polyeditor2.default) {
return _react2.default.cloneElement(child, {
__poly__: this.polygon,
__map__: this.map
});
}
return null;
}
}, {
key: 'render',
value: function render() {
return this.state.loaded ? this.renderEditor(this.props.children) : null;
}
}, {
key: 'instance',
get: function get() {
return this.polygon;
}
}]);
return Polygon;
}(_react.Component);
exports.default = (0, _withPropsReactive2.default)(Polygon);
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _withPropsReactive = require('../utils/withPropsReactive');
var _withPropsReactive2 = _interopRequireDefault(_withPropsReactive);
var _log = require('../utils/log');
var _log2 = _interopRequireDefault(_log);
var _polyeditor = require('../polyeditor');
var _polyeditor2 = _interopRequireDefault(_polyeditor);
var _common = require('../utils/common');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Component = _react2.default.Component;
var configurableProps = ['path', 'extData', 'draggable',
/* 扩展属性*/
'visible', 'style'];
var allProps = configurableProps.concat(['zIndex', 'bubble', 'showDir']);
var Polyline = function (_Component) {
_inherits(Polyline, _Component);
function Polyline(props) {
_classCallCheck(this, Polyline);
var _this = _possibleConstructorReturn(this, (Polyline.__proto__ || Object.getPrototypeOf(Polyline)).call(this, props));
if (typeof window !== 'undefined') {
if (!props.__map__) {
_log2.default.warning('MAP_INSTANCE_REQUIRED');
} else {
var self = _this;
_this.setterMap = {
visible: function visible(val) {
if (val) {
self.polyline && self.polyline.show();
} else {
self.polyline && self.polyline.hide();
}
},
style: function style(val) {
self.polyline.setOptions(val);
}
};
_this.converterMap = {
path: function path(val) {
return self.buildPathValue(val);
}
};
_this.state = {
loaded: false
};
_this.map = props.__map__;
_this.element = _this.map.getContainer();
setTimeout(function () {
_this.createMapPolyline(props);
}, 13);
}
}
return _this;
}
_createClass(Polyline, [{
key: 'createMapPolyline',
value: function createMapPolyline(props) {
var options = this.buildCreateOptions(props);
options.map = this.map;
this.polyline = new window.AMap.Polyline(options);
this.setState({
loaded: true
});
this.props.onInstanceCreated && this.props.onInstanceCreated();
}
}, {
key: 'buildCreateOptions',
value: function buildCreateOptions(props) {
var _this2 = this;
var options = {};
allProps.forEach(function (key) {
if (key in props) {
if (key === 'style' && props.style) {
var styleItem = Object.keys(props.style);
styleItem.forEach(function (item) {
// $FlowFixMe
options[item] = props.style[item];
});
// visible 做特殊处理
} else if (key !== 'visible') {
options[key] = _this2.getSetterValue(key, props[key]);
}
}
});
return options;
}
}, {
key: 'detectPropChanged',
value: function detectPropChanged(key, nextProps) {
return this.props[key] !== nextProps[key];
}
}, {
key: 'getSetterValue',
value: function getSetterValue(key, value) {
if (key in this.converterMap) {
return this.converterMap[key](value);
}
return value;
}
}, {
key: 'buildPathValue',
value: function buildPathValue(path) {
if (path.length) {
if ('getLng' in path[0]) {
return path;
}
return path.map(function (p) {
return (0, _common.toLnglat)(p);
});
}
return path;
}
}, {
key: 'renderEditor',
value: function renderEditor(children) {
if (!children) {
return null;
}
if (_react2.default.Children.count(children) !== 1) {
return null;
}
var child = _react2.default.Children.only(children);
if (child.type === _polyeditor2.default) {
return _react2.default.cloneElement(child, {
__poly__: this.polyline,
__map__: this.map
});
}
return null;
}
}, {
key: 'render',
value: function render() {
return this.state.loaded ? this.renderEditor(this.props.children) : null;
}
}, {
key: 'instance',
get: function get() {
return this.polyline;
}
}]);
return Polyline;
}(Component);
exports.default = (0, _withPropsReactive2.default)(Polyline);
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var DEFAULT_CONFIG = {
v: '1.4.0',
hostAndPath: 'webapi.amap.com/maps',
key: 'f97efc35164149d0c0f299e7a8adb3d2',
callback: '__amap_init_callback',
useAMapUI: false
};
var mainPromise = null;
var amapuiPromise = null;
var amapuiInited = false;
var APILoader = function () {
function APILoader(_ref) {
var key = _ref.key,
useAMapUI = _ref.useAMapUI,
version = _ref.version,
protocol = _ref.protocol;
_classCallCheck(this, APILoader);
this.config = _extends({}, DEFAULT_CONFIG, { useAMapUI: useAMapUI, protocol: protocol });
if (typeof window !== 'undefined') {
if (key) {
this.config.key = key;
} else if ('amapkey' in window) {
this.config.key = window.amapkey;
}
}
if (version) {
this.config.v = version;
}
this.protocol = protocol || window.location.protocol;
if (this.protocol.indexOf(':') === -1) {
this.protocol += ':';
}
}
_createClass(APILoader, [{
key: 'getScriptSrc',
value: function getScriptSrc(cfg) {
return this.protocol + '//' + cfg.hostAndPath + '?v=' + cfg.v + '&key=' + cfg.key + '&callback=' + cfg.callback;
}
}, {
key: 'buildScriptTag',
value: function buildScriptTag(src) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.defer = true;
script.src = src;
return script;
}
}, {
key: 'getAmapuiPromise',
value: function getAmapuiPromise() {
var script = this.buildScriptTag(this.protocol + '//webapi.amap.com/ui/1.0/main-async.js');
var p = new Promise(function (resolve) {
script.onload = function () {
resolve();
};
});
document.body.appendChild(script);
return p;
}
}, {
key: 'getMainPromise',
value: function getMainPromise() {
var _this = this;
var script = this.buildScriptTag(this.getScriptSrc(this.config));
var p = new Promise(function (resolve) {
window[_this.config.callback] = function () {
resolve();
delete window[_this.config.callback];
};
});
document.body.appendChild(script);
return p;
}
}, {
key: 'load',
value: function load() {
if (typeof window === 'undefined') {
return null;
}
var useAMapUI = this.config.useAMapUI;
mainPromise = mainPromise || this.getMainPromise();
if (useAMapUI) {
amapuiPromise = amapuiPromise || this.getAmapuiPromise();
}
return new Promise(function (resolve) {
mainPromise.then(function () {
if (useAMapUI && amapuiPromise) {
amapuiPromise.then(function () {
if (window.initAMapUI && !amapuiInited) {
window.initAMapUI();
if (typeof useAMapUI === 'function') {
useAMapUI();
}
amapuiInited = true;
}
resolve();
});
} else {
resolve();
}
});
});
}
}]);
return APILoader;
}();
exports.default = APILoader;
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var hasWindow = typeof window !== 'undefined';
/*
* [lng, lat]
* {lng, lat}
* {longitude, latitude}
*/
var toLnglat = exports.toLnglat = function toLnglat(pos) {
if (!pos) {
return pos;
}
// 高德原生 AMap.LngLat 类
if ('getLng' in pos && 'getLat' in pos) {
return pos;
}
var lng = 0;
var lat = 0;
if ({}.toString.call(pos) === '[object Array]') {
lng = pos[0];
lat = pos[1];
} else if ('lng' in pos && 'lat' in pos) {
lng = pos.lng;
lat = pos.lat;
} else if ('longitude' in pos && 'latitude' in pos) {
lng = pos.longitude;
lat = pos.latitude;
}
return hasWindow ? new window.AMap.LngLat(lng, lat) : null;
};
var toPixel = exports.toPixel = function toPixel(ofst) {
if (!ofst) {
return ofst;
}
if ('getX' in ofst && 'getY' in ofst) {
return ofst;
}
var x = 0;
var y = 0;
if ({}.toString.call(ofst) === '[object Array]') {
x = ofst[0];
y = ofst[1];
} else if ('x' in ofst && 'y' in ofst) {
x = ofst.x;
y = ofst.y;
}
return hasWindow ? new window.AMap.Pixel(x, y) : null;
};
var toSize = exports.toSize = function toSize(size) {
if (!size) {
return size;
}
if ('getWidth' in size) {
return size;
}
return hasWindow ? new window.AMap.Size(size.width, size.height) : null;
};
exports.default = {
toLnglat: toLnglat,
toPixel: toPixel,
toSize: toSize
};
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var isFun = function isFun(arg) {
return !!arg && typeof arg === 'function';
};
exports.default = isFun;
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var errorMap = {
'MARKER_ID_CONFLICT': 'Marker 的 id 属性重复',
'MARKER_ID_REQUIRED': '每一个 Marker 必需有一个 id 属性',
'MAP_INSTANCE_REQUIRED': '没有地图实例;组件必须作为 Map 的子组件使用',
'CIRCLE_INSTANCE_REQUIRED': '',
'CIRCLE_CENTER_REQUIRED': 'Circle 组件必需设置 center 属性',
'CIRCLE_RADIUS_REQUIRED': 'Circle 组件必需设置 radius 属性',
'SRC_REQUIRED': 'GroundImage 组件必需设置 src 属性',
'BOUNDS_REQUIRED': 'GroundImage 组件必需设置 bounds 属性',
'WINDOW_POSITION_REQUIRED': 'InfoWindow 组件必需设置 position 属性',
'INVALID_AMAP_PLUGIN': 'plugins 属性不正确;目前支持的插件有\'Scale\', \'ToolBar\', \'MapType\', \'OverView\''
};
var getMessage = function getMessage(key) {
return key in errorMap ? errorMap[key] : key;
};
var log = {
// 开发者必须修正的问题,否则会影响其他程序运行
error: function error(key) {
throw new Error(getMessage(key));
},
// 是一个错误,导致本插件无法运行,但是不会影响开发者的其他功能
warning: function warning(key) {
// console.log(`%c${getMessage(key)}`, 'color:#f66;border-left: 2px solid red;padding-left: 4px;');
console.warn(getMessage(key));
},
// 不影响使用,但不是本插件理想的使用方式
optimize: function optimize(key) {
console.log('%c' + getMessage(key), 'color:#d4d483;border-left: 2px solid #d4d483;padding-left: 4px;');
}
};
exports.default = log;
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.renderMarkerComponent = exports.getPropValue = exports.MarkerAllProps = exports.MarkerConfigurableProps = undefined;
var _common = require('./common');
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _isFun = require('./isFun');
var _isFun2 = _interopRequireDefault(_isFun);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MarkerConfigurableProps = exports.MarkerConfigurableProps = ['position', 'offset', 'icon', 'content', 'draggable', 'visible', 'zIndex', 'angle', 'animation', 'shadow', 'title', 'clickable', 'extData', 'label'];
var MarkerAllProps = exports.MarkerAllProps = MarkerConfigurableProps.concat(['topWhenClick', 'bubble', 'raiseOnDrag', 'cursor', 'autoRotation', 'shape']);
var getPropValue = exports.getPropValue = function getPropValue(key, value) {
if (MarkerAllProps.indexOf(key) === -1) {
return null;
}
if (key === 'position') {
return (0, _common.toLnglat)(value);
} else if (key === 'offset') {
return (0, _common.toPixel)(value);
}
return value;
};
var renderMarkerComponent = exports.renderMarkerComponent = function renderMarkerComponent(component, marker) {
var child = component;
if ((0, _isFun2.default)(component)) {
var extData = marker.getExtData();
child = component(extData);
}
if (child) {
(0, _reactDom.render)(_react2.default.createElement(
'div',
null,
child
), marker.getContent());
}
};
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var toCapitalString = function toCapitalString(str) {
return str[0].toUpperCase() + str.slice(1, str.length);
};
exports.default = toCapitalString;
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _toCapitalString = require('./toCapitalString');
var _toCapitalString2 = _interopRequireDefault(_toCapitalString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function withPropsReactive(MapComponent) {
return function (_React$Component) {
_inherits(_class, _React$Component);
function _class(props) {
_classCallCheck(this, _class);
var _this = _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).call(this, props));
_this.instanceCreated = false;
_this.myMapComponent = null;
_this.registeredEvents = [];
_this.onInstanceCreated = _this.onInstanceCreated.bind(_this);
return _this;
}
_createClass(_class, [{
key: 'onInstanceCreated',
value: function onInstanceCreated() {
this.instanceCreated = true;
if ('events' in this.props) {
var instance = this.myMapComponent.instance;
if (this.props.events.created) {
this.props.events.created(instance);
}
}
this.reactivePropChange(this.props, false);
}
}, {
key: 'createEventsProxy',
value: function createEventsProxy(props) {
var self = this;
var instance = this.myMapComponent.instance;
var evs = Object.keys(props.events || {});
evs.length && evs.forEach(function (ev) {
if (self.registeredEvents.indexOf(ev) === -1) {
self.registeredEvents.push(ev);
instance.on(ev, function (ev) {
return function () {
if (self.props.events && ev in self.props.events) {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
self.props.events[ev].apply(null, args);
}
};
}(ev));
}
});
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
this.reactivePropChange(nextProps, true);
}
}, {
key: 'reactivePropChange',
value: function reactivePropChange(nextProps) {
var _this2 = this;
var shouldDetectChange = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (!this.instanceCreated) {
return false;
}
var _myMapComponent = this.myMapComponent,
_myMapComponent$sette = _myMapComponent.setterMap,
setterMap = _myMapComponent$sette === undefined ? {} : _myMapComponent$sette,
_myMapComponent$conve = _myMapComponent.converterMap,
converterMap = _myMapComponent$conve === undefined ? {} : _myMapComponent$conve,
_myMapComponent$insta = _myMapComponent.instance,
instance = _myMapComponent$insta === undefined ? {} : _myMapComponent$insta;
var list = Object.keys(nextProps);
list.length && list.forEach(function (key) {
if (key === 'events') {
return _this2.createEventsProxy(nextProps);
}
var willReactive = true;
if (shouldDetectChange) {
willReactive = _this2.detectPropChange(key, nextProps, _this2.props);
}
if (!willReactive) {
return false;
}
var setterParam = nextProps[key];
if (key in converterMap) {
setterParam = converterMap[key](nextProps[key]);
}
if (key in setterMap) {
setterMap[key](setterParam);
} else {
var trySetterName = 'set' + (0, _toCapitalString2.default)(key);
if (trySetterName in instance) {
instance[trySetterName](setterParam);
}
}
});
}
}, {
key: 'detectPropChange',
value: function detectPropChange(key, nextProps, oldProps) {
return nextProps[key] !== oldProps[key];
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
return _react2.default.createElement(MapComponent, _extends({
onInstanceCreated: this.onInstanceCreated,
ref: function ref(comp) {
_this3.myMapComponent = comp;
}
}, this.props));
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
var instance = this.myMapComponent.instance;
if (!instance) return;
if ('destroy' in instance) {
setTimeout(function () {
instance.destroy();
}, 10);
}
if ('hide' in instance) {
instance.hide();
}
if ('__map__' in this.props && 'setMap' in instance) {
instance.setMap(null);
}
}
}]);
return _class;
}(_react2.default.Component);
};
exports.default = withPropsReactive;
\ No newline at end of file
{
"_from": "react-amap",
"_id": "react-amap@1.2.8",
"_inBundle": false,
"_integrity": "sha512-uHPEUXti+CcwFyCeqGGqR0ACnXJA9D8S/lQYal9AG3XEOrwkaOFbWUavrvXxjcfAclROIWg8uKxzlRpMQnkHFg==",
"_location": "/react-amap",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "react-amap",
"name": "react-amap",
"escapedName": "react-amap",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/react-amap/-/react-amap-1.2.8.tgz",
"_shasum": "cb5a6441c5e83acb0d7b2e8a1b20dc539b759d9b",
"_spec": "react-amap",
"_where": "/Users/wangduo/workspace/packages/react-native-amap-sdk",
"author": {
"name": "ohislh@gmail.com"
},
"bugs": {
"url": "https://github.com/ElemeFE/react-amap/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "AMap Component Based On React",
"devDependencies": {
"@types/react": "^16.0.10",
"antd": "^2.7.4",
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-eslint": "^7.1.1",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.23.0",
"babel-preset-stage-0": "^6.22.0",
"bisheng": "0.13.3",
"bisheng-plugin-antd": "0.3.2",
"bisheng-plugin-react": "0.2.2",
"css-loader": "^0.26.1",
"dora-plugin-proxy": "^0.8.5",
"eslint": "^3.17.1",
"eslint-config-elemefe": "^0.2.0",
"eslint-loader": "^1.9.0",
"eslint-plugin-flowtype": "^2.30.3",
"eslint-plugin-react": "^6.10.0",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^0.10.0",
"flow-bin": "^0.56.0",
"html-webpack-plugin": "^2.28.0",
"isomorphic-style-loader": "^1.1.0",
"jsonml-to-react-component": "^0.2.6",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-router": "^3.0.2",
"style-loader": "^0.13.1",
"uglify-js": "^2.8.12",
"url-loader": "^0.5.7",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
},
"homepage": "https://github.com/ElemeFE/react-amap",
"keywords": [
"map",
"react"
],
"license": "MIT",
"main": "lib/index.js",
"name": "react-amap",
"repository": {
"type": "git",
"url": "git+https://github.com/elemefe/react-amap.git"
},
"scripts": {
"browser-build": "rm -rf dist && webpack && NODE_ENV=production webpack -p",
"deploy": "npm run npm-build && bisheng gh-pages",
"flow": "flow; test $? -eq 0 -o $? -eq 2",
"lint": "eslint . --quiet",
"npm-build": "rm -rf lib && babel components -d lib",
"prepublish": "npm run browser-build && npm run npm-build",
"site": "npm run npm-build && bisheng build",
"start": "npm run npm-build && bisheng start"
},
"types": "types/index.d.ts",
"version": "1.2.8"
}
/// <reference types="react" />
import * as React from 'react';
export type EventMap = Object;
export type PluginList = 'Scale' | 'ToolBar' | 'MapType' | 'OverView' | 'ControlBar'
export interface PluginConfig {
name: PluginList;
options?: Object;
}
export type ArrayLngLat = [number, number];
export interface LngLatPos {
lng: number;
lat: number;
}
export interface FullLngLatPos {
longitude: number;
latitude: number;
}
export interface AMapLngLat {
offset(): AMapLngLat;
distance(): number;
getLng(): number;
getLat(): number;
equanls(): boolean;
toString(): string;
}
export type LngLat = ArrayLngLat | LngLatPos | FullLngLatPos | AMapLngLat;
export type Path = Array<ArrayLngLat> | Array<FullLngLatPos> | Array<AMapLngLat>;
export type PolygonPath = Path | [Path, Path];
export type ArrayPixel = [number, number];
export interface AMapPixel {
getX(): number;
getY(): number;
equals(): boolean;
toString(): string;
}
export type Pixel = AMapPixel | ArrayPixel;
export interface ObjSize {
width: number;
height: number;
}
export interface AMapSize {
getWidth(): number;
getHeight(): number;
toString(): string;
}
export type Size = ObjSize | AMapSize;
export type MapFeature = 'bg' | 'point' | 'road' | 'building';
export interface MapProps {
protocol?: string;
amapkey?: string;
version?: string;
useAMapUI?: boolean | Function;
children?: any;
onInstanceCreated?: Function;
plugins?: Array<PluginList|PluginConfig>;
events?: EventMap;
loading?: any;
viewMode?: '2D'|'3D';
center?: LngLat;
zoom?: number;
zooms?: [number, number];
animateEnable?: boolean;
doubleClickZoom?: boolean;
dragEnable?: boolean;
isHotspot?: boolean;
jogEnable?: boolean;
keyboardEnable?: boolean;
resizeEnable?: boolean;
rotateEnable?: boolean;
scrollWheel?: boolean;
touchZoom?: boolean;
zoomEnable?: boolean;
showIndoorMap?: boolean;
expandZoomRange?: boolean;
pitch?: number;
mapStyle?: string;
labelzIndex?: number;
skyColor?: string;
buildingAnimation?: boolean;
pitchEnable?: boolean;
showBuildingBlock?: boolean;
features?: Array<MapFeature>;
indoorMap?: any;
cursor?: string;
layers?: Array<any>;
view?: any;
city?: string;
bounds?: any;
limitBounds?: any;
status?: any;
rotation?: number;
}
export interface MarkerProps {
position?: LngLat;
offset?: Pixel;
icon?: any;
onInstanceCreated?: Function;
className?: string;
content?: string | HTMLElement;
draggable?: boolean;
visible?: boolean;
cursor?: string;
zIndex?: number;
angle?: number;
animation?: string;
markers?: Array<Object>;
shadow?: Object;
title?: string;
clickable?: boolean;
extData?: any;
label?: Object;
topWhenClick?: boolean;
bubble?: boolean;
raiseOnDrag?: boolean;
autoRotation?: boolean;
shape?: Object;
events?: Object;
render?: Function;
children?: any;
useCluster?: Object | boolean;
}
export interface CircleProps {
center: LngLat;
radius: number;
draggable?: boolean;
extData?: any;
visible?: boolean;
style?: Object;
zIndex?: number;
bubble: boolean;
events?: Object;
children?: any;
}
export interface CircleEditorProps {
active?: boolean;
events?: EventMap;
}
export interface PolygonProps {
path: PolygonPath;
draggable?: boolean;
extData?: any;
style?: Object;
visible?: boolean;
zIndex?: number;
bubble?: boolean;
events?: Object;
children?: any;
}
export interface PolylineProps {
path: Path;
extData?: any;
draggable?: boolean;
visible?: boolean;
style?: Object;
zIndex?: number;
bubble?: boolean;
showDir?: boolean;
events?: Object;
children?: any;
}
export interface PolyEditorProps {
active?: boolean;
events?: EventMap;
}
export interface GroungImageProps {
opacity?: number;
src?: string;
bounds: Object;
visible?: boolean;
clickable?: boolean;
events?: EventMap;
}
export interface InfoWindowProps {
content?: any;
position: LngLat;
size?: Size;
visible?: boolean;
offset?: Pixel;
isCustom?: boolean;
autoMove?: boolean;
closeWhenClickMap?: boolean;
showShadow?: boolean;
events?: EventMap;
children?: any;
className?: string;
}
export interface MouseToolProps {
events?: EventMap;
}
export class Map extends React.Component<MapProps, {mapLoaded: boolean}> {}
export class Marker extends React.Component<MarkerProps, {}> {}
export class Markers extends React.Component<any, any> {}
export class Circle extends React.Component<CircleProps, {}> {}
export class CircleEditor extends React.Component<CircleEditorProps, {}> {}
export class Polygon extends React.Component<PolygonProps, {}> {}
export class Polyline extends React.Component<PolylineProps, {}> {}
export class PolyEditor extends React.Component<PolyEditorProps, {}> {}
export class GroundImage extends React.Component<GroungImageProps, {}> {}
export class InfoWindow extends React.Component<InfoWindowProps, {}> {}
export class MouseTool extends React.Component<MouseToolProps, {}> {}
{
"name": "@hisense/react-native-amap-sdk",
"version": "2.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"react-amap": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/react-amap/-/react-amap-1.2.8.tgz",
"integrity": "sha512-uHPEUXti+CcwFyCeqGGqR0ACnXJA9D8S/lQYal9AG3XEOrwkaOFbWUavrvXxjcfAclROIWg8uKxzlRpMQnkHFg=="
}
}
}
{
"files": [
"android",
"ios",
"index.js",
"index.web.js",
"app",
"readme.md"
],
"name": "@hisense/react-native-amap-sdk",
"license": "MIT",
"author": "Allen.Chiang",
"version": "2.0.0",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"react",
"native",
"amap",
"location"
],
"main": "main.js",
"dependencies": {
"prop-types": "15.6.1",
"react-amap": "^1.2.8"
},
"description": "React Native AMap component for iOS + Android +Web"
}
.idea/
.gradle/
node_modules/
build/
xcuserdata/
Pods/
*.iml
*.xcworkspace
local.properties
Podfile.lock
package-lock.json
yarn.lock
\ No newline at end of file
# RNAMapLocation 此分支为2D地图的分支,3D地图见 master3d 分支
高德api封装使用ReactNative结构,包含定位,地图,地图标注,地理编码,逆地理编码,poi兴趣点,导航等功能
amap 的文档参考https://github.com/qiuxiang/react-native-amap3d, 改了 mapview 组件的一些东西,修改后的内容参考demo
## Version
** v 2.0.0 **
### 安装
- 添加npm依赖
package.json的depencency中添加:
```
"@terminus/react-native-amap-sdk": "2.0.2-amap2d.1"
```
或者
npm install @terminus/react-native-amap-sdk@2.0.0-amap2d --save
- 项目导入
1.iOS 建议使用cocoapods依赖方式, `Podfile`文件添加如下
```
pod 'react-native-amap-sdk/LocationAmap', :path => '../node_modules/@terminus/react-native-amap-sdk/ios'
pod 'react-native-amap-sdk/Map3dAmap', :path => '../node_modules/@terminus/react-native-amap-sdk/ios'
```
然后执行 `pod upodate `方法
2.安卓集成
在settings.gradle 文件中加入如下
```
// 只有poi 和 获取 定位坐标信息的, 没有地图组件
include ':react-native-amap-sdk'
project(':react-native-amap-sdk').projectDir = new File(rootProject.projectDir, '../node_modules/@terminus/react-native-amap-sdk/android/locationamap')
// 只有地图相关控件(如mark,折线,多边围栏等)
include ':react-native-3damap-sdk'
project(':react-native-3damap-sdk').projectDir = new File(rootProject.projectDir, '../node_modules/@terminus/react-native-amap-sdk/android/map3damap')
```
在application的app模块下的build.gradle 中添加如下
```
compile project(":react-native-amap-sdk")
compile project(":react-native-3damap-sdk")
```
在MainApplication的代码中加入如下
```
import cn.qiuxiang.react.amap3d.AMap3DPackage;
import io.terminus.rnamap.AMapReactPackage;
......
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
......
new AMapReactPackage(),
new AMap3DPackage()
......
);
}
};
```
- 应用权限配置
在iOS应用info.plist中添加如下配置
```
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>NSLocationWhenInUseUsageDescription</key>
<string>需要使用您的定位信息</string>
```
- 高德AppKey配置
iOS工程配置
AppDelegate类`-[AppDelegate application:didFinishLaunchingWithOptions:]`方法中添加如下行
```
#import "RNAMConfig.h"
......
-[AppDelegate application:didFinishLaunchingWithOptions:]
......
[RNAMConfig setAppKey: @"请输入您的用户Key"];
......
```
Android工程配置
`Manifest`文件中添加如下行
```
<meta-data android:name="com.amap.api.v2.apikey" android:value="请输入您的用户Key"/>
```
### 使用
#### 定位模块
1. 获取当前那位置
** 使用说明 **
```
import {fetchLocation} from '@terminus/react-native-amap-sdk';
···
fetchLocation((lp, error) => {
if (error) {
console.log('location', error.code, error.message)
return
}
// 定位成功 根据定位信息做相关处理
});
```
** 参数说明 **
lp :相关当前定位信息,包含data和requestId,其中,data中即包含当前定位信息,如下所示:
| 参数名 | 描述 | 类型 |
|:-------------: |:-------------: |:-----:|
|latitude| gps坐标信息 |string |
| longitude |gps坐标信息 | string |
| formattedAddress |格式化地址| string |
| country |国家| string |
| province |省/直辖市| string |
| city |市| string |
| district |区| string |
| citycode |城市编码| string |
| adcode |区域编码| string |
| street |街道名称| string |
| number |门牌号| string |
| POIName |兴趣点名称| string |
| AOIName |所属兴趣点名称| string |
| pois |poi列表| object |
#### 地图模块
** 使用说明 **
amap 的文档参考https://github.com/qiuxiang/react-native-amap3d, 改了 mapview 组件的一些东西,修改后的内容参考demo
#### 地图功能模块
1. 地理编码
** 使用说明 **
```
import {AMapGeocode} from '@terminus/react-native-amap-sdk';
...
// 根据地址和城市信息进行地理编码
AMapGeocode(address,city).then((data)=>{
const geocode = data.list[0];
// 获取到位置信息
this.setState({
geocodeResult : `${geocode.latitude},${geocode.longitude}`
})
})
```
** 参数说明 **
结果返回为
```
data:list(array类型)
```
其中:list数组中返回的就是相关地理编码信息,
list中的返回对象参数信息如下:
| 参数名 | 描述 | 类型 |
|:-------------: |:-------------: |:-----:|
|latitude| gps坐标信息 |string |
| longitude |gps坐标信息 | string |
| formattedAddress |格式化地址| string |
| country |国家| string |
| province |省/直辖市| string |
| city |市| string |
| district |区| string |
| citycode |城市编码| string |
| adcode |区域编码| string |
| street |街道名称| string |
| number |门牌号| string |
| POIName |兴趣点名称| string |
| AOIName |所属兴趣点名称| string |
| pois |poi列表| object |
2. 逆地理编码
** 使用说明 **
根据经纬度进行逆地理编码
```
import {AMapReGeocode} from '@terminus/react-native-amap-sdk';
...
const latitude = '30.179339'
const longitude = '120.14156'
AMapReGeocode(latitude,longitude).then((data)=>{
// 获取当前位置信息
})
```
** 参数说明 **
返回的data即是当前位置信息,详细说明见定位模块中的定位信息列表。
3. poi数据
** 使用说明 **
```
import { AMapPOISearchPage,AMapPOISearch
} from '@terminus/react-native-amap-sdk';
...
// poi搜索
AMapPOISearch(keywords,city,).then((data) =>{
if(data.pois){
})
}
});
// poi搜索 (设定搜索页)
AMapPOISearchPage(keywords,city,pageNum,pageSize).then((data) =>{
if(data.pois){
})
}
});
```
** 参数说明 **
- 传入参数
| 参数名 | 描述 | 类型 |
|:-------------: |:-------------: |:-----:|
|keywords| poi关键字 |string |
| city |限定城市(cityName/cityCode/adcode) |string |
| pageNum |限定页数| string |
| pageSize |每页记录数| string |
- 搜索结果
返回结果如下所示:
```
data:{
count:0,// poi总数量
pois:[],// poi数据列表
suggestions:[] // 关键字建议列表和城市建议列表
}
```
其中,pois数组中就是所需要的poi数据信息,poi数据中可能的参数信息如下:
| 参数名 | 描述 | 类型 |
|:-------------: |:-------------: |:-----:|
|uid | POI全局唯一ID | string|
|name| 名称 |string |
|type|兴趣点类型 |string |
|typecode| 类型编码 |string |
|location| 经纬度 |string |
|address|地址 |string |
|tel|电话 |string |
|distance|距离 |string |
|parkingType| 停车场类型|string |
|shopID| 商铺id |string |
|postcode| 邮编 |string |
|website| 网址 |string |
|email| 电子邮件 |string |
|province| 省 |string |
|pcode| 省编码 |string |
|city| 城市名称 |string |
|citycode| 城市编码 |string |
|district| 区域名称 |string |
|adcode| 区域编码 |string |
|gridcode| 地理格ID |string |
|enterLocation| 入口经纬度 |string |
|exitLocation| 出口经纬度 |string |
|direction| 方向 |string |
|hasIndoorMap| 是否有室内地图 |bool |
|businessArea| 所在商圈 |string |
|indoorData| 室内信息 |string |
|subPOIs| 子POI列表 |array |
|images| 图片列表 |array |
#### 导航功能模块
** 使用说明 **
支持使用高德地图导航,iOS可选自带地图导航
```
import {mapNavigation} from '@terminus/react-native-amap-sdk';
...
mapNavigation(
{sname:'我的位置',
slat:30.179415,
slon:120.138031,
dname:'云栖小镇',
dlat:30.132344,
dlon:120.083468}
)
```
** 参数说明 **
导航参数配置说明
| 参数名 | 描述 | 类型 |
|:-------------: |:-------------: |:-----:|
|sname| 初始位置描述 |string |
| slat |出发地gps信息 |string |
| slon |出发地gps信息| string |
| dname |目的地描述| string |
| dlat |目的地gps信息| string |
| dlon |目的地gps信息| string |
#### web使用
支持使用高德地图web获取当前位置
```
import { setAmapKey, fetchLocation } from '@terminus/react-native-amap-sdk';
setAmapKey('xxxx', 'AMap.Geocoder') // 如果没有引入地图script,则必须先设置 地图的key
fetchLocation((lp, error) => {
if (error) {
console.log('location', error.code, error.message)
return
}
// 定位成功 根据定位信息做相关处理
});
```
** 参数说明 **
lp :相关当前定位信息,与react-native的相关参数并不完全一致, data中即包含当前定位信息,缺失的信息如下所示:
| 参数名 | 描述 | 类型 |
|:-------------: |:-------------: |:-----:|
| country |国家| string |
| POIName |兴趣点名称| string |
| AOIName |所属兴趣点名称| string |
### mapview模块
## 功能
- 地图模式切换(常规、卫星、导航、夜间)
- 3D 建筑、路况、室内地图
- 内置地图控件的显示隐藏(指南针、比例尺、定位按钮、缩放按钮)
- 手势交互控制(平移、缩放、旋转、倾斜)
- 中心坐标、缩放级别、倾斜度的设置,支持动画过渡
- 地图事件(onPress、onLongPress、onLocation、onStatusChange)
- 地图标记(Marker)
- 自定义信息窗体
- 自定义图标
- 折线绘制(Polyline)
- 多边形绘制(Polygon)
- 圆形绘制(Circle)
- 热力图(HeatMap)
- 海量点(MultiPoint)
- 离线地图
<img src="https://user-images.githubusercontent.com/1709072/40894475-907865ea-67dc-11e8-83f3-09ac73c95434.jpg" width="215"> <img src="https://user-images.githubusercontent.com/1709072/40894476-90ac38d4-67dc-11e8-9667-a4c36ef897bc.jpg" width="215"> <img src="https://user-images.githubusercontent.com/1709072/40894477-90dd258e-67dc-11e8-8809-e8f4e3198cee.jpg" width="215"> <img src="https://user-images.githubusercontent.com/1709072/40894478-91a87720-67dc-11e8-9135-c64680ad70eb.jpg" width="215">
## 用法
### 导入地图模块
```jsx
import { MapView } from 'react-native-amap3d'
```
### 基本用法
```jsx
<MapView
coordinate={{
latitude: 39.91095,
longitude: 116.37296,
}}
/>
```
### 启用定位并监听定位事件
```jsx
<MapView
locationEnabled
onLocation={({ nativeEvent }) =>
console.log(`${nativeEvent.latitude}, ${nativeEvent.longitude}`)}
/>
```
### 添加可拖拽的地图标记
```jsx
<MapView>
<MapView.Marker
draggable
title='这是一个可拖拽的标记'
onDragEnd={({ nativeEvent }) =>
console.log(`${nativeEvent.latitude}, ${nativeEvent.longitude}`)}
coordinate={{
latitude: 39.91095,
longitude: 116.37296,
}}
/>
</MapView>
```
### 自定义标记图片及信息窗体
```jsx
const coordinate = {
latitude: 39.706901,
longitude: 116.397972,
}
<MapView.Marker image='flag' coordinate={coordinate}>
<View style={styles.customInfoWindow}>
<Text>自定义信息窗体</Text>
</View>
</MapView.Marker>
```
## 接口
请参考注释文档:
- [MapView](app/amap3d/maps/MapView.js) 位置: app/amap3d/maps/MapView.js
- [Marker](app/amap3d/maps/Marker.js) 位置: app/amap3d/maps/Marker.js
- [Polyline](app/amap3d/maps/Polyline.js) 位置: app/amap3d/maps/Polyline.js
- [Polygon](app/amap3d/maps/Polygon.js) 位置: app/amap3d/maps/Polygon.js
- [Circle](app/amap3d/maps/Circle.js) 位置: app/amap3d/maps/Circle.js
- [HeatMap](app/amap3d/maps/HeatMap.js) 位置: app/amap3d/maps/HeatMap.js
- [MultiPoint](app/amap3d/maps/MultiPoint.js) 位置: app/amap3d/maps/MultiPoint.js
更多功能查看example 或下载项目中的 app-release.apk, 可执行adb install -r app-release.apk进行安装
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment