diff --git a/DistributedMapDemo/README.md b/DistributedMapDemo/README.md index de47143df49c0d38588306d37a483109a3f3b68f..08a5133d8938c65d6d6549605a7f247dff14f405 100644 --- a/DistributedMapDemo/README.md +++ b/DistributedMapDemo/README.md @@ -43,4 +43,4 @@ Note • If you run it on the phone, you need to configure the signature and certificate information in the project's File> Project Structure> Modules> Signing Configs. Licensing -Please see LICENSE for more info. +Please see LICENSE for more info. \ No newline at end of file diff --git a/DistributedMapDemo/entry/build.gradle b/DistributedMapDemo/entry/build.gradle index 266a8abbcb70bb85ffaa039ececa4e23ae4251dc..3b47bf86f299921b7ac6b5605944e507da274e58 100644 --- a/DistributedMapDemo/entry/build.gradle +++ b/DistributedMapDemo/entry/build.gradle @@ -9,4 +9,5 @@ ohos { dependencies { implementation fileTree(dir: 'libs', include: ['*.jar', '*.har']) implementation 'com.google.code.gson:gson:2.8.0' + implementation project(":tinymap") } diff --git a/DistributedMapDemo/entry/src/main/config.json b/DistributedMapDemo/entry/src/main/config.json index 79255ed0d41ab85dfe27504cc99513418f13caf7..b8e48634c785f47ffcf89cd44b21d998af857e94 100644 --- a/DistributedMapDemo/entry/src/main/config.json +++ b/DistributedMapDemo/entry/src/main/config.json @@ -20,7 +20,7 @@ "deliveryWithInstall": true, "moduleName": "entry", "moduleType": "entry", - "installationFree": false + "installationFree": false }, "abilities": [ { diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/MainAbility.java b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/MainAbility.java index 5479471642ff551fe67878f322ca2ede8ab62ac5..aaaa54f14c4cd9212faea0024c19d03f6c932f56 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/MainAbility.java +++ b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/MainAbility.java @@ -16,6 +16,7 @@ package com.huawei.codelab; import com.huawei.codelab.slice.MainAbilitySlice; +import com.huawei.codelab.slice.WatchAbilitySlice; import com.huawei.codelab.util.LogUtils; import com.huawei.codelab.util.PermissionsUtils; @@ -23,6 +24,8 @@ import ohos.aafwk.ability.Ability; import ohos.aafwk.ability.IAbilityContinuation; import ohos.aafwk.content.Intent; import ohos.aafwk.content.IntentParams; +import ohos.data.distributed.common.KvManagerConfig; +import ohos.data.distributed.common.KvManagerFactory; import ohos.security.SystemPermission; /** @@ -33,12 +36,20 @@ import ohos.security.SystemPermission; public class MainAbility extends Ability implements IAbilityContinuation { private static final String TAG = MainAbility.class.getSimpleName(); + private static final String DEVICE_TYPE_WATCH = "109"; + private String[] requestPermissions = {SystemPermission.DISTRIBUTED_DATASYNC, SystemPermission.LOCATION}; @Override public void onStart(Intent intent) { super.onStart(intent); - super.setMainRoute(MainAbilitySlice.class.getName()); + String deviceType = + KvManagerFactory.getInstance().createKvManager(new KvManagerConfig(this)).getLocalDeviceInfo().getType(); + if (deviceType.equals(DEVICE_TYPE_WATCH)) { + super.setMainRoute(WatchAbilitySlice.class.getName()); + } else { + super.setMainRoute(MainAbilitySlice.class.getName()); + } PermissionsUtils.getInstance().requestPermissions(this, requestPermissions); } diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/bean/InputTipsResult.java b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/bean/InputTipsResult.java index 4d16d2e2a0701a6bd373e1012cc297d6efcef015..4b3f567e7f2cdcca59684a509876a9ddcabe4d5d 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/bean/InputTipsResult.java +++ b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/bean/InputTipsResult.java @@ -23,32 +23,12 @@ import java.util.List; * @since 2021-03-12 */ public class InputTipsResult { - private String count; - - private String infocode; - private List tips; private String status; private String info; - public String getCount() { - return count; - } - - public void setCount(String count) { - this.count = count; - } - - public String getInfocode() { - return infocode; - } - - public void setInfocode(String infocode) { - this.infocode = infocode; - } - public List getTips() { return tips; } @@ -80,8 +60,6 @@ public class InputTipsResult { * @since 2021-03-12 */ public static class TipsEntity { - private String typecode; - private E address; private E adcode; @@ -90,24 +68,36 @@ public class InputTipsResult { private String location; - public String getTypecode() { - return typecode; - } - public E getAddress() { return address; } + public void setAddress(E address) { + this.address = address; + } + public E getAdcode() { return adcode; } + public void setAdcode(E adcode) { + this.adcode = adcode; + } + public String getName() { return name; } + public void setName(String name) { + this.name = name; + } + public String getLocation() { return location; } + + public void setLocation(String location) { + this.location = location; + } } } diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/bean/RegionDetailResult.java b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/bean/RegionDetailResult.java index 79763605754c65e991141813f50021b83bc47cf0..51f4d87d200fdfd527e215de94b3611711694da8 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/bean/RegionDetailResult.java +++ b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/bean/RegionDetailResult.java @@ -15,30 +15,16 @@ package com.huawei.codelab.bean; -import java.util.List; - /** * RegionDetailResult * * @since 2021-03-12 */ public class RegionDetailResult { - private String infocode; - private RegeocodeEntity regeocode; private String status; - private String info; - - public String getInfocode() { - return infocode; - } - - public void setInfocode(String infocode) { - this.infocode = infocode; - } - public RegeocodeEntity getRegeocode() { return regeocode; } @@ -55,32 +41,14 @@ public class RegionDetailResult { this.status = status; } - public String getInfo() { - return info; - } - - public void setInfo(String info) { - this.info = info; - } - /** * RegeocodeEntity * * @since 2021-03-12 */ public class RegeocodeEntity { - private String formattedAddress; - private AddressComponentEntity addressComponent; - public String getFormattedAddress() { - return formattedAddress; - } - - public void setFormattedAddress(String formattedAddress) { - this.formattedAddress = formattedAddress; - } - public AddressComponentEntity getAddressComponent() { return addressComponent; } @@ -95,54 +63,8 @@ public class RegionDetailResult { * @since 2021-03-12 */ public class AddressComponentEntity { - private List> businessAreas; - - private String country; - - private String province; - private String citycode; - private String city; - - private String adcode; - - private StreetNumberEntity streetNumber; - - private String towncode; - - private String district; - - private BuildingEntity neighborhood; - - private String township; - - private BuildingEntity building; - - public List> getBusinessAreas() { - return businessAreas; - } - - public void setBusinessAreas(List> businessAreas) { - this.businessAreas = businessAreas; - } - - 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 getCitycode() { return citycode; } @@ -150,154 +72,6 @@ public class RegionDetailResult { public void setCitycode(String citycode) { this.citycode = citycode; } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public String getAdcode() { - return adcode; - } - - public void setAdcode(String adcode) { - this.adcode = adcode; - } - - public StreetNumberEntity getStreetNumber() { - return streetNumber; - } - - public void setStreetNumber(StreetNumberEntity streetNumber) { - this.streetNumber = streetNumber; - } - - public String getTowncode() { - return towncode; - } - - public void setTowncode(String towncode) { - this.towncode = towncode; - } - - public String getDistrict() { - return district; - } - - public void setDistrict(String district) { - this.district = district; - } - - public BuildingEntity getNeighborhood() { - return neighborhood; - } - - public void setNeighborhood(BuildingEntity neighborhood) { - this.neighborhood = neighborhood; - } - - public String getTownship() { - return township; - } - - public void setTownship(String township) { - this.township = township; - } - - public BuildingEntity getBuilding() { - return building; - } - - public void setBuilding(BuildingEntity building) { - this.building = building; - } - - /** - * StreetNumberEntity - * - * @since 2021-03-12 - */ - public class StreetNumberEntity { - private String number; - - private String distance; - - private String street; - - private String location; - - private String direction; - - public String getNumber() { - return number; - } - - public void setNumber(String number) { - this.number = number; - } - - public String getDistance() { - return distance; - } - - public void setDistance(String distance) { - this.distance = distance; - } - - public String getStreet() { - return street; - } - - public void setStreet(String street) { - this.street = street; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - - public String getDirection() { - return direction; - } - - public void setDirection(String direction) { - this.direction = direction; - } - } - - /** - * BuildingEntity - * - * @since 2021-03-12 - */ - public class BuildingEntity { - private List name; - - private List type; - - public List getName() { - return name; - } - - public void setName(List name) { - this.name = name; - } - - public List getType() { - return type; - } - - public void setType(List type) { - this.type = type; - } - } } } } diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/bean/RouteResult.java b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/bean/RouteResult.java index 2c0db5fa57b68e8f1109cbd2d5bfda617bf6423e..cb7148e5bc4398a81084865b638feb0346ff42d5 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/bean/RouteResult.java +++ b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/bean/RouteResult.java @@ -25,10 +25,6 @@ import java.util.List; public class RouteResult { private RouteEntity route; - private String count; - - private String infocode; - private String status; private String info; @@ -41,22 +37,6 @@ public class RouteResult { this.route = route; } - public String getCount() { - return count; - } - - public void setCount(String count) { - this.count = count; - } - - public String getInfocode() { - return infocode; - } - - public void setInfocode(String infocode) { - this.infocode = infocode; - } - public String getStatus() { return status; } @@ -81,12 +61,6 @@ public class RouteResult { public class RouteEntity { private List paths; - private String origin; - - private String destination; - - private String taxiCost; - public List getPaths() { return paths; } @@ -95,100 +69,14 @@ public class RouteResult { this.paths = paths; } - public String getOrigin() { - return origin; - } - - public void setOrigin(String origin) { - this.origin = origin; - } - - public String getDestination() { - return destination; - } - - public void setDestination(String destination) { - this.destination = destination; - } - - public String getTaxiCost() { - return taxiCost; - } - - public void setTaxiCost(String taxiCost) { - this.taxiCost = taxiCost; - } - /** * PathsEntity * * @since 2021-03-12 */ public class PathsEntity { - private String duration; - - private String distance; - - private String restriction; - - private String tollDistance; - - private String strategy; - - private String trafficLights; - private List steps; - private String tolls; - - public String getDuration() { - return duration; - } - - public void setDuration(String duration) { - this.duration = duration; - } - - public String getDistance() { - return distance; - } - - public void setDistance(String distance) { - this.distance = distance; - } - - public String getRestriction() { - return restriction; - } - - public void setRestriction(String restriction) { - this.restriction = restriction; - } - - public String getTollDistance() { - return tollDistance; - } - - public void setTollDistance(String tollDistance) { - this.tollDistance = tollDistance; - } - - public String getStrategy() { - return strategy; - } - - public void setStrategy(String strategy) { - this.strategy = strategy; - } - - public String getTrafficLights() { - return trafficLights; - } - - public void setTrafficLights(String trafficLights) { - this.trafficLights = trafficLights; - } - public List getSteps() { return steps; } @@ -197,14 +85,6 @@ public class RouteResult { this.steps = steps; } - public String getTolls() { - return tolls; - } - - public void setTolls(String tolls) { - this.tolls = tolls; - } - /** * StepsEntity * @@ -212,104 +92,12 @@ public class RouteResult { * @since 2021-03-12 */ public class StepsEntity { - private String orientation; - - private String distance; - - private List cities; - - private E tollRoad; - - private String tollDistance; - - private String tolls; - - private String duration; - - private E assistantAction; - - private String road; - private String instruction; private E action; private String polyline; - private List tmcs; - - public String getOrientation() { - return orientation; - } - - public void setOrientation(String orientation) { - this.orientation = orientation; - } - - public String getDistance() { - return distance; - } - - public void setDistance(String distance) { - this.distance = distance; - } - - public List getCities() { - return cities; - } - - public void setCities(List cities) { - this.cities = cities; - } - - public E getTollRoad() { - return tollRoad; - } - - public void setTollRoad(E tollRoad) { - this.tollRoad = tollRoad; - } - - public String getTollDistance() { - return tollDistance; - } - - public void setTollDistance(String tollDistance) { - this.tollDistance = tollDistance; - } - - public String getTolls() { - return tolls; - } - - public void setTolls(String tolls) { - this.tolls = tolls; - } - - public String getDuration() { - return duration; - } - - public void setDuration(String duration) { - this.duration = duration; - } - - public E getAssistantAction() { - return assistantAction; - } - - public void setAssistantAction(E assistantAction) { - this.assistantAction = assistantAction; - } - - public String getRoad() { - return road; - } - - public void setRoad(String road) { - this.road = road; - } - public String getInstruction() { return instruction; } @@ -333,135 +121,6 @@ public class RouteResult { public void setPolyline(String polyline) { this.polyline = polyline; } - - public List getTmcs() { - return tmcs; - } - - public void setTmcs(List tmcs) { - this.tmcs = tmcs; - } - - /** - * CitiesEntity - * - * @since 2021-03-12 - */ - public class CitiesEntity { - private String citycode; - - private String adcode; - - private String name; - - private List districts; - - 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 getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getDistricts() { - return districts; - } - - public void setDistricts(List districts) { - this.districts = districts; - } - - /** - * DistrictsEntity - * - * @since 2021-03-12 - */ - public class DistrictsEntity { - private String adcode; - - private String name; - - public String getAdcode() { - return adcode; - } - - public void setAdcode(String adcode) { - this.adcode = adcode; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - } - } - - /** - * TmcsEntity - * - * @since 2021-03-12 - */ - public class TmcsEntity { - private String distance; - - private E lcode; - - private String polyline; - - private String status; - - public String getDistance() { - return distance; - } - - public void setDistance(String distance) { - this.distance = distance; - } - - public E getLcode() { - return lcode; - } - - public void setLcode(E lcode) { - this.lcode = lcode; - } - - public String getPolyline() { - return polyline; - } - - public void setPolyline(String polyline) { - this.polyline = polyline; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - } } } } diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/map/Const.java b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/map/Const.java index f32fa2fa097e35ead649f1a31c7c64562b091d1f..cef1f046be7b7b6358488336679447d3bcc4e8a4 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/map/Const.java +++ b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/map/Const.java @@ -22,16 +22,10 @@ package com.huawei.codelab.map; */ public class Const { /** - * 接口的调用凭证,需要开发者自己申请 + * 高德地图接口的调用凭证,需要开发者自己申请 */ public static final String MAP_KEY = "fdec31f36248c7aa50dd2d252cc773e2"; - /** - * 高德地图导航瓦片url - */ - public static final String TILE_URL = - "https://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=2&style=8&x=%d&y=%d&z=%d"; - /** * 高德地图输入提示api接口 */ diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/map/MapDataHelper.java b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/map/MapDataHelper.java index 5f5ce9afc28e3806937a6eb581ae269376a49710..959e6efd9fa469ded9f1faeeaefdbb739051177d 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/map/MapDataHelper.java +++ b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/map/MapDataHelper.java @@ -23,6 +23,10 @@ import com.huawei.codelab.util.HttpUtils; import com.huawei.codelab.util.LogUtils; import com.huawei.codelab.util.MapUtils; +import com.dongyu.tinymap.Element; +import com.dongyu.tinymap.TinyMap; + +import ohos.agp.components.TextField; import ohos.agp.utils.Point; import ohos.app.Context; @@ -38,7 +42,7 @@ public class MapDataHelper { private String location; - private NavMap navMap; + private TinyMap tinyMap; private Context context; @@ -49,11 +53,11 @@ public class MapDataHelper { /** * 构造方法 * - * @param navMap navMap + * @param tinyMap navMap * @param context context */ - public MapDataHelper(NavMap navMap, Context context) { - this.navMap = navMap; + public MapDataHelper(TinyMap tinyMap, Context context) { + this.tinyMap = tinyMap; this.context = context; } @@ -72,27 +76,33 @@ public class MapDataHelper { /** * 获取本机位置信息 + * + * @param startLocationText start location Component */ - public void getMyLocation() { + public void getMyLocation(TextField startLocationText) { new LocationHelper().getMyLocation(context, loc -> { double locLongitude = loc.getLongitude(); double locLatitude = loc.getLatitude(); location = locLongitude + "," + locLatitude; - if (navMap.getMapElements() == null) { + if (tinyMap.getMapElements() == null) { setMapCenter(locLongitude, locLatitude); - getRegionDetail(); + getRegionDetail(startLocationText); } }); } /** * 调用高德地图逆地理编码api,获取城市编码 + * + * @param startLocationText start location Component */ - private void getRegionDetail() { + private void getRegionDetail(TextField startLocationText) { String url = String.format(Const.REGION_DETAIL_URL, location, Const.MAP_KEY); HttpUtils.getInstance(context).get(url, result -> { RegionDetailResult regionDetailResult = GsonUtils.jsonToBean(result, RegionDetailResult.class); localCityCode = regionDetailResult.getRegeocode().getAddressComponent().getCitycode(); + startLocationText.setText("我的位置"); + LogUtils.info(TAG, "localCityCode:" + localCityCode); }); } @@ -120,7 +130,12 @@ public class MapDataHelper { */ public void getRouteResult(String endLocation) { String url = String.format(Const.ROUTE_URL, location, endLocation, Const.MAP_KEY); - HttpUtils.getInstance(context).get(url, result -> dataCallBack.setRouteView(result)); + HttpUtils.getInstance(context).get(url, result -> { + dataCallBack.setBottomView(); + tinyMap.setStepPoint(0); + tinyMap.getMapElements().clear(); + parseRoute(result); + }); } /** @@ -129,7 +144,6 @@ public class MapDataHelper { * @param result 高德地图路径规划api返回的结果 */ public void parseRoute(String result) { - navMap.getMapElements().clear(); RouteResult routeResult = GsonUtils.jsonToBean(result, RouteResult.class); List paths = routeResult.getRoute().getPaths(); RouteResult.RouteEntity.PathsEntity pathsEntity = paths.get(0); @@ -177,17 +191,17 @@ public class MapDataHelper { public void setMapCenter(double lon, double lat) { double[] mercators = MapUtils.lonLat2Mercator(lon, lat); Point centerPoint = new Point((float) mercators[0], (float) mercators[1]); - navMap.setCenterPoint(centerPoint); - MapElement peopleEle = new MapElement(centerPoint.getPointX(), centerPoint.getPointY(), true); + tinyMap.setCenterPoint(centerPoint); + Element peopleEle = new Element(centerPoint.getPointX(), centerPoint.getPointY(), true); peopleEle.setActionType(Const.ROUTE_PEOPLE); - navMap.addElement(peopleEle); + tinyMap.addElement(peopleEle); } private void addElementToMap(double[] coordinates, String actionType, String content, boolean isImage) { - MapElement mapElementEnd = new MapElement((float) coordinates[0], (float) coordinates[1], isImage); - mapElementEnd.setActionType(actionType); - mapElementEnd.setActionContent(content); - navMap.addElement(mapElementEnd); + Element elementEnd = new Element((float) coordinates[0], (float) coordinates[1], isImage); + elementEnd.setActionType(actionType); + elementEnd.setActionContent(content); + tinyMap.addElement(elementEnd); } /** @@ -204,10 +218,8 @@ public class MapDataHelper { void setInputTipsView(List tips); /** - * 设置导航路径视图 - * - * @param route route + * 设置底部视图 */ - void setRouteView(String route); + void setBottomView(); } } diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/map/MapManager.java b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/map/MapManager.java index d55226c9be0504250c283ddb28326aa5725aba29..0f1bde3ad5d2dea740efa8bb7758545b5a35f58e 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/map/MapManager.java +++ b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/map/MapManager.java @@ -22,6 +22,9 @@ import com.huawei.codelab.WatchService; import com.huawei.codelab.bean.InputTipsResult; import com.huawei.codelab.util.LogUtils; +import com.dongyu.tinymap.Element; +import com.dongyu.tinymap.TinyMap; + import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.ability.IAbilityConnection; import ohos.aafwk.content.Intent; @@ -53,9 +56,9 @@ public class MapManager { private int stepPoint = 0; - private MapElement nextElement; + private Element nextElement; - private NavMap navMap; + private TinyMap tinyMap; private AbilitySlice slice; @@ -89,8 +92,8 @@ public class MapManager { @Override public void run() { // 将定位图标的下一个坐标点的坐标,赋值给当前定位图标 - MapElement peopleElement = navMap.getMapElements().get(0); - nextElement = navMap.getMapElements().get(stepPoint + 1); + Element peopleElement = tinyMap.getMapElements().get(0); + nextElement = tinyMap.getMapElements().get(stepPoint + 1); peopleElement.setMercatorPoint(nextElement.getMercatorPoint()); peopleElement.setNowPoint(nextElement.getNowPoint()); peopleElement.setOriginPoint(nextElement.getOriginPoint()); @@ -103,9 +106,9 @@ public class MapManager { stepPoint++; // 将stepPoint传递给NavMap,绘制已经过的路径时也会用到stepPoint - navMap.setStepPoint(stepPoint); + tinyMap.setStepPoint(stepPoint); LogUtils.info(TAG, "run......" + stepPoint); - if (stepPoint >= navMap.getMapElements().size() - 1) { + if (stepPoint >= tinyMap.getMapElements().size() - 1) { mapEventHandler.removeTask(task); } } @@ -114,11 +117,11 @@ public class MapManager { /** * 构造方法 * - * @param navMap navMap + * @param tinyMap navMap * @param slice slice */ - public MapManager(NavMap navMap, AbilitySlice slice) { - this.navMap = navMap; + public MapManager(TinyMap tinyMap, AbilitySlice slice) { + this.tinyMap = tinyMap; this.slice = slice; mapEventHandler = new MapEventHandler(EventRunner.current()); } @@ -228,16 +231,19 @@ public class MapManager { requestRemote(Const.STOP_WATCH_ABILITY, ""); mapEventHandler.removeTask(task); stepPoint = 0; - navMap.setStepPoint(0); - navMap.getMapElements().clear(); - navMap.invalidate(); + tinyMap.setStepPoint(0); + tinyMap.getMapElements().clear(); + tinyMap.invalidate(); } /** * 迁移 + * + * @param deviceId selected deviceId */ - public void translate() { - slice.continueAbility(); + public void translate(String deviceId) { + slice.continueAbility(deviceId); + // 关闭WatchAbility requestRemote(Const.STOP_WATCH_ABILITY, ""); } @@ -245,8 +251,8 @@ public class MapManager { * 迁移完成后的回调 */ public void translateComplete() { - navMap.getMapElements().clear(); - navMap.invalidate(); + tinyMap.getMapElements().clear(); + tinyMap.invalidate(); mapEventHandler.removeTask(task); } @@ -257,11 +263,11 @@ public class MapManager { */ public interface NavListener { /** - * 监听回调 + * 监听回调,将数据会调给MainAbilitySlice * - * @param mapElement MapElement + * @param element MapElement */ - void onNavListener(MapElement mapElement); + void onNavListener(Element element); } /** @@ -280,15 +286,16 @@ public class MapManager { if (event.eventId != 1) { return; } - LogUtils.info(TAG, "processEvent invalidate"); if (nextElement.getActionType() != null && !nextElement.getActionType().isEmpty()) { + // 将nextElement回调给MainAbilitySlice navListener.onNavListener(nextElement); } if (proxy != null) { + // 将数据发送给WatchService requestRemote(nextElement.getActionType() == null ? "" : nextElement.getActionType(), nextElement.getActionContent() == null ? "" : nextElement.getActionContent()); } - navMap.invalidate(); + tinyMap.invalidate(); } } } diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/provider/InputTipsProvider.java b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/provider/InputTipsProvider.java index 81b117529d2341b7c77f4547651988fe80a3db3a..4e69481e715e038b1c695c102e123a60ccbde1e8 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/provider/InputTipsProvider.java +++ b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/provider/InputTipsProvider.java @@ -72,12 +72,10 @@ public class InputTipsProvider extends BaseItemProvider { if (component == null) { component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_input_tips, null, false); viewHolder = new ViewHolder(); - if (component.findComponentById(ResourceTable.Id_tips_name) instanceof Text) { - viewHolder.tipsName = (Text) component.findComponentById(ResourceTable.Id_tips_name); - } - if (component.findComponentById(ResourceTable.Id_tips_detail) instanceof Text) { - viewHolder.tipsDetail = (Text) component.findComponentById(ResourceTable.Id_tips_detail); - } + + viewHolder.tipsName = (Text) component.findComponentById(ResourceTable.Id_tips_name); + viewHolder.tipsDetail = (Text) component.findComponentById(ResourceTable.Id_tips_detail); + component.setTag(viewHolder); } else { if (component.getTag() instanceof ViewHolder) { diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/slice/MainAbilitySlice.java b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/slice/MainAbilitySlice.java index 3efa12c799eaa62abdc45d4c40c8c0f423d7f02d..75e90e82c07c949f378eee79fdc457424ebcfb33 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/slice/MainAbilitySlice.java +++ b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/slice/MainAbilitySlice.java @@ -18,17 +18,23 @@ package com.huawei.codelab.slice; import com.huawei.codelab.ResourceTable; import com.huawei.codelab.bean.InputTipsResult; import com.huawei.codelab.map.MapDataHelper; -import com.huawei.codelab.map.MapElement; import com.huawei.codelab.map.MapManager; -import com.huawei.codelab.map.NavMap; import com.huawei.codelab.provider.InputTipsProvider; import com.huawei.codelab.util.GsonUtils; -import com.huawei.codelab.util.ImageUtils; import com.huawei.codelab.util.LogUtils; import com.huawei.codelab.util.PermissionsUtils; +import com.dongyu.tinymap.Element; +import com.dongyu.tinymap.TinyMap; +import com.dongyu.tinymap.util.ImageUtils; + import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.ability.IAbilityContinuation; +import ohos.aafwk.ability.continuation.DeviceConnectState; +import ohos.aafwk.ability.continuation.ExtraParams; +import ohos.aafwk.ability.continuation.IContinuationDeviceCallback; +import ohos.aafwk.ability.continuation.IContinuationRegisterManager; +import ohos.aafwk.ability.continuation.RequestCallback; import ohos.aafwk.content.Intent; import ohos.aafwk.content.IntentParams; import ohos.agp.components.Button; @@ -65,9 +71,9 @@ public class MainAbilitySlice extends AbilitySlice private DependentLayout routeTipsLayout; - private NavMap navMap; + private TinyMap tinyMap; - private List elements; + private List elements; private TextField startTextField; @@ -105,6 +111,39 @@ public class MainAbilitySlice extends AbilitySlice private int stepPoint = 0; + // 注册流转任务管理服务后返回的Ability token + private int abilityToken; + + // 用户在设备列表中选择设备后返回的设备ID + private String selectDeviceId; + + // 获取流转任务管理服务管理类 + private IContinuationRegisterManager continuationRegisterManager; + + // 设置流转任务管理服务设备状态变更的回调 + private IContinuationDeviceCallback callback = new IContinuationDeviceCallback() { + @Override + public void onDeviceConnectDone(String deviceId, String deviceType) { + // 在用户选择设备后设置设备ID + selectDeviceId = deviceId; + LogUtils.info(TAG, "onDeviceConnectDone:"); + translate(); + } + + @Override + public void onDeviceDisconnectDone(String deviceId) { + LogUtils.info(TAG, "onDeviceDisconnectDone:" + deviceId); + } + }; + + // 设置注册流转任务管理服务回调 + private RequestCallback requestCallback = new RequestCallback() { + @Override + public void onResult(int result) { + abilityToken = result; + } + }; + @Override public void onStart(Intent intent) { super.onStart(intent); @@ -116,57 +155,19 @@ public class MainAbilitySlice extends AbilitySlice } private void findComponentById() { - if (findComponentById(ResourceTable.Id_map) instanceof NavMap) { - navMap = (NavMap) findComponentById(ResourceTable.Id_map); - } - - if (findComponentById(ResourceTable.Id_start_point_field) instanceof TextField) { - startTextField = (TextField) findComponentById(ResourceTable.Id_start_point_field); - } - - if (findComponentById(ResourceTable.Id_end_point_field) instanceof TextField) { - endTextField = (TextField) findComponentById(ResourceTable.Id_end_point_field); - } - - if (findComponentById(ResourceTable.Id_route_content) instanceof Text) { - routeContent = (Text) findComponentById(ResourceTable.Id_route_content); - } - - if (findComponentById(ResourceTable.Id_route_tips) instanceof DependentLayout) { - routeTipsLayout = (DependentLayout) findComponentById(ResourceTable.Id_route_tips); - } - - if (findComponentById(ResourceTable.Id_route_img) instanceof Image) { - routeImage = (Image) findComponentById(ResourceTable.Id_route_img); - } - - if (findComponentById(ResourceTable.Id_list_input_tips) instanceof ListContainer) { - listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_input_tips); - } - - if (findComponentById(ResourceTable.Id_layout_input_tips) instanceof DependentLayout) { - inputTipsLayout = (DependentLayout) findComponentById(ResourceTable.Id_layout_input_tips); - } - - if (findComponentById(ResourceTable.Id_select_point) instanceof DirectionalLayout) { - selectPointLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_select_point); - } - - if (findComponentById(ResourceTable.Id_nav_bottom) instanceof DirectionalLayout) { - navBottom = (DirectionalLayout) findComponentById(ResourceTable.Id_nav_bottom); - } - - if (findComponentById(ResourceTable.Id_start_nav) instanceof Button) { - btnStartNav = (Button) findComponentById(ResourceTable.Id_start_nav); - } - - if (findComponentById(ResourceTable.Id_end_nav) instanceof Button) { - btnEndNav = (Button) findComponentById(ResourceTable.Id_end_nav); - } - - if (findComponentById(ResourceTable.Id_nav_translate) instanceof Button) { - navTranslate = (Button) findComponentById(ResourceTable.Id_nav_translate); - } + tinyMap = (TinyMap) findComponentById(ResourceTable.Id_map); + startTextField = (TextField) findComponentById(ResourceTable.Id_start_point_field); + endTextField = (TextField) findComponentById(ResourceTable.Id_end_point_field); + routeContent = (Text) findComponentById(ResourceTable.Id_route_content); + routeTipsLayout = (DependentLayout) findComponentById(ResourceTable.Id_route_tips); + routeImage = (Image) findComponentById(ResourceTable.Id_route_img); + listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_input_tips); + inputTipsLayout = (DependentLayout) findComponentById(ResourceTable.Id_layout_input_tips); + selectPointLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_select_point); + navBottom = (DirectionalLayout) findComponentById(ResourceTable.Id_nav_bottom); + btnStartNav = (Button) findComponentById(ResourceTable.Id_start_nav); + btnEndNav = (Button) findComponentById(ResourceTable.Id_end_nav); + navTranslate = (Button) findComponentById(ResourceTable.Id_nav_translate); } private void setListener() { @@ -179,14 +180,18 @@ public class MainAbilitySlice extends AbilitySlice mapDataHelper.setDataCallBack(this); - mapManager.setNavListener(mapElement -> { - routeContent.setText(mapElement.getActionContent()); - routeImage.setPixelMap(ImageUtils.getImageId(mapElement.getActionType())); + mapManager.setNavListener(element -> { + routeContent.setText(element.getActionContent()); + routeImage.setPixelMap(ImageUtils.getImageId(element.getActionType())); }); PermissionsUtils.getInstance().setRequestListener(permission -> { if (permission.equals(SystemPermission.LOCATION)) { - mapDataHelper.getMyLocation(); + mapDataHelper.getMyLocation(startTextField); + initContinuationRegisterManager(); + } + if (permission.equals(SystemPermission.DISTRIBUTED_DATASYNC)) { + initContinuationRegisterManager(); } }); @@ -216,14 +221,18 @@ public class MainAbilitySlice extends AbilitySlice } private void initView() { - mapDataHelper = new MapDataHelper(navMap, this); - mapManager = new MapManager(navMap, this); + mapDataHelper = new MapDataHelper(tinyMap, this); + mapManager = new MapManager(tinyMap, this); // 解决ListContainer和NavMap的Touch事件冲突 listContainer.setTouchEventListener((component, touchEvent) -> true); if (verifySelfPermission(SystemPermission.LOCATION) == IBundleManager.PERMISSION_GRANTED) { - mapDataHelper.getMyLocation(); + mapDataHelper.getMyLocation(startTextField); + } + + if (verifySelfPermission(SystemPermission.DISTRIBUTED_DATASYNC) == IBundleManager.PERMISSION_GRANTED) { + initContinuationRegisterManager(); } if (elements != null) { @@ -234,17 +243,20 @@ public class MainAbilitySlice extends AbilitySlice btnStartNav.setVisibility(Component.HIDE); selectPointLayout.setVisibility(Component.HIDE); - navMap.setStepPoint(stepPoint); + tinyMap.setStepPoint(stepPoint); mapManager.setStepPoint(stepPoint); Point mercatorPoint = elements.get(0).getMercatorPoint(); - navMap.setCenterPoint(new Point(mercatorPoint.getPointX(), mercatorPoint.getPointY())); + tinyMap.setCenterPoint(new Point(mercatorPoint.getPointX(), mercatorPoint.getPointY())); // 将元素集合添加到navMap对象,并重新计算坐标 - for (MapElement mapElement : elements) { - navMap.addElement(mapElement); + for (Element element : elements) { + tinyMap.addElement(element); } - mapManager.startNav(); + // 到达终点 + if (stepPoint < elements.size() - 1) { + mapManager.startNav(); + } } } @@ -275,13 +287,44 @@ public class MainAbilitySlice extends AbilitySlice } } + private void initContinuationRegisterManager() { + continuationRegisterManager = getContinuationRegisterManager(); + // 增加过滤条件 + ExtraParams params = new ExtraParams(); + String[] devTypes = new String[] {ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE, + ExtraParams.DEVICETYPE_SMART_WATCH}; + params.setDevType(devTypes); + // 注册流转任务管理服务 + continuationRegisterManager.register(getBundleName(), params, callback, requestCallback); + } + + private void translate() { + getUITaskDispatcher().asyncDispatch(() -> { + if (continuationRegisterManager != null) { + continuationRegisterManager.updateConnectStatus(abilityToken, selectDeviceId, + DeviceConnectState.IDLE.getState(), null); + if (selectDeviceId != null) { + LogUtils.info(TAG, "translate:" + abilityToken); + // 用户点击后发起迁移流程 + mapManager.translate(selectDeviceId); + } + } + }); + } + @Override public void onClick(Component component) { switch (component.getId()) { // 迁移 case ResourceTable.Id_nav_translate: - mapManager.translate(); - setTranslateView(); + // 设置过滤设备类型 + ExtraParams params = new ExtraParams(); + String[] devTypes = new String[] {ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE, + ExtraParams.DEVICETYPE_SMART_WATCH}; + params.setDevType(devTypes); + + // 显示选择设备列表 + continuationRegisterManager.showDeviceList(abilityToken, params, null); break; // 开始导航 @@ -300,10 +343,6 @@ public class MainAbilitySlice extends AbilitySlice } } - private void setTranslateView() { - navTranslate.setVisibility(Component.HIDE); - } - private void setStartNavView() { btnStartNav.setVisibility(Component.HIDE); selectPointLayout.setVisibility(Component.HIDE); @@ -330,11 +369,8 @@ public class MainAbilitySlice extends AbilitySlice } @Override - public void setRouteView(String route) { - navMap.getMapElements().clear(); + public void setBottomView() { navBottom.setVisibility(Component.VISIBLE); - navMap.setStepPoint(0); - mapDataHelper.parseRoute(route); } @Override @@ -350,10 +386,10 @@ public class MainAbilitySlice extends AbilitySlice @Override public boolean onSaveData(IntentParams saveData) { - String elementsString = GsonUtils.objectToString(navMap.getMapElements()); + String elementsString = GsonUtils.objectToString(tinyMap.getMapElements()); saveData.setParam(ELEMENT_STRING, elementsString); saveData.setParam("stepPoint", mapManager.getStepPoint()); - LogUtils.info(TAG, "onSaveData" + navMap.getMapElements().size()); + LogUtils.info(TAG, "onSaveData" + tinyMap.getMapElements().size()); return true; } @@ -361,7 +397,7 @@ public class MainAbilitySlice extends AbilitySlice public boolean onRestoreData(IntentParams restoreData) { if (restoreData.getParam(ELEMENT_STRING) instanceof String) { String elementsString = (String) restoreData.getParam(ELEMENT_STRING); - elements = GsonUtils.jsonToList(elementsString, MapElement.class); + elements = GsonUtils.jsonToList(elementsString, Element.class); } stepPoint = (int) restoreData.getParam("stepPoint"); LogUtils.info(TAG, "onRestoreData::elements::" + elements.size()); @@ -371,7 +407,8 @@ public class MainAbilitySlice extends AbilitySlice @Override public void onCompleteContinuation(int result) { mapManager.translateComplete(); + navTranslate.setVisibility(Component.HIDE); routeTipsLayout.setVisibility(Component.HIDE); - LogUtils.info(TAG, "onCompleteContinuation"); + LogUtils.info(TAG, "onCompleteContinuation result:" + result); } } diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/slice/WatchAbilitySlice.java b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/slice/WatchAbilitySlice.java index 3afc8c84c606deac972e577c7dcdfab3f2c4550b..e04ad36527392f84703d57ac32d7b2cfe42c40f5 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/slice/WatchAbilitySlice.java +++ b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/slice/WatchAbilitySlice.java @@ -55,12 +55,8 @@ public class WatchAbilitySlice extends AbilitySlice { } private void findComponentById() { - if (findComponentById(ResourceTable.Id_action_content) instanceof Text) { - contentComponent = (Text) findComponentById(ResourceTable.Id_action_content); - } - if (findComponentById(ResourceTable.Id_action_img) instanceof Image) { - actionImg = (Image) findComponentById(ResourceTable.Id_action_img); - } + contentComponent = (Text) findComponentById(ResourceTable.Id_action_content); + actionImg = (Image) findComponentById(ResourceTable.Id_action_img); } private void subscribe() { diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/util/ImageUtils.java b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/util/ImageUtils.java index a7c1f705bffd6d5013fca7876ae1c5df4f1180f1..47687faddb7cb606198baeac2e8fbb867594cadb 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/util/ImageUtils.java +++ b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/util/ImageUtils.java @@ -18,31 +18,12 @@ package com.huawei.codelab.util; import com.huawei.codelab.ResourceTable; import com.huawei.codelab.map.Const; -import ohos.app.Context; -import ohos.global.resource.NotExistException; -import ohos.media.image.ImageSource; -import ohos.media.image.PixelMap; -import ohos.media.image.common.Size; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; - /** * MapHelper * * @since 2021-02-01 */ public class ImageUtils { - private static final String TAG = ImageUtils.class.getName(); - - private static final int TILE_LENGTH = 513; - - private static final int TIME_OUT = 5 * 1000; - - private static final int IMAGE_WIDTH_HEIGHT = 80; - private ImageUtils() { } @@ -84,68 +65,4 @@ public class ImageUtils { } return imageId; } - - /** - * getPixelMap - * - * @param context context - * @param actionType actionType - * @return PixelMap - */ - public static PixelMap getPixelMap(Context context, String actionType) { - InputStream drawableInputStream = null; - PixelMap pixelMap = null; - try { - drawableInputStream = context.getResourceManager().getResource(ImageUtils.getImageId(actionType)); - ImageSource imageSource = ImageSource.create(drawableInputStream, new ImageSource.SourceOptions()); - ImageSource.DecodingOptions options = new ImageSource.DecodingOptions(); - options.desiredSize = new Size(IMAGE_WIDTH_HEIGHT, IMAGE_WIDTH_HEIGHT); - pixelMap = imageSource.createPixelmap(options); - return pixelMap; - } catch (IOException | NotExistException exception) { - LogUtils.info(TAG, "getPixelMap:" + exception.getMessage()); - } finally { - if (drawableInputStream != null) { - try { - drawableInputStream.close(); - } catch (IOException e) { - LogUtils.info(TAG, "getPixelMap:" + e.getMessage()); - } - } - } - return pixelMap; - } - - /** - * 从网络获取地图瓦片数据 - * - * @param urlString urlString - * @return PixelMap - */ - public static PixelMap getMapPixelMap(String urlString) { - InputStream is = null; - PixelMap pixelMap = null; - try { - URL url = new URL(urlString); - URLConnection con = url.openConnection(); - con.setConnectTimeout(TIME_OUT); - is = con.getInputStream(); - ImageSource source = ImageSource.create(is, new ImageSource.SourceOptions()); - ImageSource.DecodingOptions options = new ImageSource.DecodingOptions(); - options.desiredSize = new Size(TILE_LENGTH, TILE_LENGTH); - pixelMap = source.createPixelmap(options); - return pixelMap; - } catch (IOException exception) { - LogUtils.info(TAG, "getImagePixelMap:" + exception.getMessage()); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - LogUtils.info(TAG, "getImagePixelMap:" + e.getMessage()); - } - } - } - return pixelMap; - } } diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/util/PermissionsUtils.java b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/util/PermissionsUtils.java index 2f4497ef1b2bfcc18b9d56c8ef45b4975e7718af..96c7ec0b3ce635358b52774e56fd48d152cd717f 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/util/PermissionsUtils.java +++ b/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/util/PermissionsUtils.java @@ -88,7 +88,9 @@ public class PermissionsUtils { } for (int i = 0; i < grantResults.length; i++) { if (grantResults[i] == IBundleManager.PERMISSION_GRANTED) { - requestListener.permissionGranted(permissions[i]); + if (requestListener != null) { + requestListener.permissionGranted(permissions[i]); + } } else { LogUtils.info(TAG, "user deny permission:" + permissions[i]); } diff --git a/DistributedMapDemo/entry/src/main/resources/base/layout/ability_main.xml b/DistributedMapDemo/entry/src/main/resources/base/layout/ability_main.xml index 78479b169b866959c7f77bfe15718fecf6a23015..11fc4433fcee4d45bd27018c57a0e35e6df02d9c 100644 --- a/DistributedMapDemo/entry/src/main/resources/base/layout/ability_main.xml +++ b/DistributedMapDemo/entry/src/main/resources/base/layout/ability_main.xml @@ -9,7 +9,7 @@ ohos:height="match_content" ohos:width="match_parent"> - mapTiles; + private List tiles; - private List elements; + private List elements; private Paint paint; @@ -109,7 +118,7 @@ public class NavMap extends Component implements Component.DrawTask, Component.T * @param attrSet AttrSet */ - public NavMap(Context context, AttrSet attrSet) { + public TinyMap(Context context, AttrSet attrSet) { super(context, attrSet); initPaint(); } @@ -135,7 +144,7 @@ public class NavMap extends Component implements Component.DrawTask, Component.T * * @return 类型为List */ - public List getMapElements() { + public List getMapElements() { return elements; } @@ -156,21 +165,21 @@ public class NavMap extends Component implements Component.DrawTask, Component.T /** * 往地图中添加地图元素 * - * @param mapElement 地图元素 + * @param element 地图元素 */ - public void addElement(MapElement mapElement) { + public void addElement(Element element) { if (elements == null) { elements = new ArrayList<>(0); } double componentX = - (mapElement.getMercatorPoint().getPointX() - centerPoint.getPointX()) / tileRealLength * TILE_LENGTH + (element.getMercatorPoint().getPointX() - centerPoint.getPointX()) / tileRealLength * TILE_LENGTH + mapComponentWidth / COMPONENT_HALF; double componentY = - (centerPoint.getPointY() - mapElement.getMercatorPoint().getPointY()) / tileRealLength * TILE_LENGTH + (centerPoint.getPointY() - element.getMercatorPoint().getPointY()) / tileRealLength * TILE_LENGTH + mapComponentHeight / COMPONENT_HALF; - mapElement.setNowPoint(new Point((float) componentX, (float) componentY)); - mapElement.setOriginPoint(new Point((float) componentX, (float) componentY)); - elements.add(mapElement); + element.setNowPoint(new Point((float) componentX, (float) componentY)); + element.setOriginPoint(new Point((float) componentX, (float) componentY)); + elements.add(element); invalidate(); } @@ -180,13 +189,16 @@ public class NavMap extends Component implements Component.DrawTask, Component.T * @param isRefresh 是否为刷新 */ public void initMapCanvas(boolean isRefresh) { - // 在某个缩放级别下,瓦片的行数(列数) + // 在某个缩放级别下,瓦片的行数(列数)32500 int rowCount = (int) Math.pow(COMPONENT_HALF, ZOOM); tileRealLength = OVER_LENGTH * COMPONENT_HALF / rowCount; mapComponentWidth = ScreenUtils.getScreenWidth(getContext()); mapComponentHeight = ScreenUtils.getScreenHeight(getContext()); + // 地图四边范围 坐标为摩卡托影坐标 + // mapComponentWidth / COMPONENT_HALF_F / TILE_LENGTH * tileRealLength摩卡托影长度的一半 double minX = centerPoint.getPointX() - mapComponentWidth / COMPONENT_HALF_F * tileRealLength / TILE_LENGTH; + // 切片范围 多少行多少列 到 多少行多少列 colMin = (int) Math.floor((minX + OVER_LENGTH) / tileRealLength); double maxX = centerPoint.getPointX() + mapComponentWidth / COMPONENT_HALF_F * tileRealLength / TILE_LENGTH; colMax = Math.min((int) Math.floor((maxX + OVER_LENGTH) / tileRealLength), rowCount - 1); @@ -208,10 +220,10 @@ public class NavMap extends Component implements Component.DrawTask, Component.T * @param isRefresh 是否为刷新 */ private void initTiles(boolean isRefresh) { - if (mapTiles == null || isRefresh) { - mapTiles = new CopyOnWriteArrayList<>(); + if (tiles == null || isRefresh) { + tiles = new CopyOnWriteArrayList<>(); } - mapTiles.removeIf(mapTile -> !mapTile.isInBoundary(rowMin, rowMax, colMin, colMax)); + tiles.removeIf(tile -> !tile.isInBoundary(rowMin, rowMax, colMin, colMax)); getContext().getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(this::setTiles); } @@ -219,7 +231,7 @@ public class NavMap extends Component implements Component.DrawTask, Component.T private void setTiles() { for (int row = rowMin; row <= rowMax; row++) { for (int col = colMin; col <= colMax; col++) { - String urlString = String.format(Const.TILE_URL, col, row, ZOOM); + String urlString = String.format(TILE_URL, col, row, ZOOM); if (hasThisTile(row, col)) { continue; @@ -236,18 +248,18 @@ public class NavMap extends Component implements Component.DrawTask, Component.T + mapComponentWidth / COMPONENT_HALF; double componentY = (centerPoint.getPointY() - tileY) / tileRealLength * TILE_LENGTH + mapComponentHeight / COMPONENT_HALF; - MapTile mapTile = new MapTile(pixelMap, (float) componentX, (float) componentY); - mapTile.setCol(col); - mapTile.setRow(row); - mapTiles.add(mapTile); + Tile tile = new Tile(pixelMap, (float) componentX, (float) componentY); + tile.setCol(col); + tile.setRow(row); + tiles.add(tile); getContext().getUITaskDispatcher().asyncDispatch(this::invalidate); } } } private boolean hasThisTile(int row, int col) { - for (MapTile mapTile : mapTiles) { - if (mapTile.getRow() == row && mapTile.getCol() == col) { + for (Tile tile : tiles) { + if (tile.getRow() == row && tile.getCol() == col) { return true; } } @@ -281,15 +293,15 @@ public class NavMap extends Component implements Component.DrawTask, Component.T } private void drawTiles(Canvas canvas) { - for (MapTile mapTile : mapTiles) { - canvas.drawPixelMapHolder(mapTile, mapTile.getNowPointX(), mapTile.getNowPointY(), linePaint); + for (Tile tile : tiles) { + canvas.drawPixelMapHolder(tile, tile.getNowPointX(), tile.getNowPointY(), linePaint); } } private void drawRoutePath(Canvas canvas) { for (int i = 1; i < elements.size(); i++) { - MapElement mapElement = elements.get(i); - Point point = mapElement.getNowPoint(); + Element element = elements.get(i); + Point point = element.getNowPoint(); float pointX = point.getPointX(); float pointY = point.getPointY(); if (i == 1 || i == elements.size() - 1) { @@ -315,7 +327,7 @@ public class NavMap extends Component implements Component.DrawTask, Component.T } private void drawImageElement(Canvas canvas) { - for (MapElement element : elements) { + for (Element element : elements) { if (element.isImage()) { PixelMapHolder pmh = new PixelMapHolder(ImageUtils.getPixelMap(getContext(), element.getActionType())); canvas.drawPixelMapHolder(pmh, element.getNowPointX() - LEFT_MARGIN, @@ -337,13 +349,11 @@ public class NavMap extends Component implements Component.DrawTask, Component.T // move if (touchEvent.getAction() == TouchEvent.POINT_MOVE) { - for (MapTile mapTile : mapTiles) { - mapTile.setNowPointX( - (point.getX() - component.getContentPositionX()) - touchedDownX + mapTile.getOriginX()); - mapTile.setNowPointY( - (point.getY() - component.getContentPositionY()) - touchedDownY + mapTile.getOriginY()); + for (Tile tile : tiles) { + tile.setNowPointX((point.getX() - component.getContentPositionX()) - touchedDownX + tile.getOriginX()); + tile.setNowPointY((point.getY() - component.getContentPositionY()) - touchedDownY + tile.getOriginY()); } - for (MapElement element : elements) { + for (Element element : elements) { element.setNowPointX( (point.getX() - component.getContentPositionX()) - touchedDownX + element.getOriginX()); element.setNowPointY( @@ -360,16 +370,14 @@ public class NavMap extends Component implements Component.DrawTask, Component.T + (point.getY() - component.getContentPositionY() - touchedDownY) / TILE_LENGTH * tileRealLength); centerPoint = new Point(newCenterPointX, newCenterPointY); - for (MapTile mapTile : mapTiles) { - mapTile.setNowPointX( - (point.getX() - component.getContentPositionX()) - touchedDownX + mapTile.getOriginX()); - mapTile.setNowPointY( - (point.getY() - component.getContentPositionY()) - touchedDownY + mapTile.getOriginY()); - mapTile.setOriginX(mapTile.getNowPointX()); - mapTile.setOriginY(mapTile.getNowPointY()); + for (Tile tile : tiles) { + tile.setNowPointX((point.getX() - component.getContentPositionX()) - touchedDownX + tile.getOriginX()); + tile.setNowPointY((point.getY() - component.getContentPositionY()) - touchedDownY + tile.getOriginY()); + tile.setOriginX(tile.getNowPointX()); + tile.setOriginY(tile.getNowPointY()); } - for (MapElement element : elements) { + for (Element element : elements) { element.setNowPointX( (point.getX() - component.getContentPositionX()) - touchedDownX + element.getOriginX()); element.setNowPointY( diff --git a/DistributedMapDemo/tinymap/src/main/java/com/dongyu/tinymap/util/Const.java b/DistributedMapDemo/tinymap/src/main/java/com/dongyu/tinymap/util/Const.java new file mode 100644 index 0000000000000000000000000000000000000000..236f0add5294d5a140669b048f438049ab4370df --- /dev/null +++ b/DistributedMapDemo/tinymap/src/main/java/com/dongyu/tinymap/util/Const.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License,Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.dongyu.tinymap.util; + +/** + * 地图导航常量封装 + * + * @since 2021-03-12 + */ +public class Const { + + /** + * 导航开始标识 + */ + public static final String ROUTE_START = "route_start"; + + /** + * 导航结束标识 + */ + public static final String ROUTE_END = "route_end"; + + /** + * 当前位置标识 + */ + public static final String ROUTE_PEOPLE = "route_people"; + + /** + * 右转标识 + */ + public static final String ROUTE_TURN_RIGHT = "右转"; + + /** + * 左转标识 + */ + public static final String ROUTE_TURN_LEFT = "左转"; + + /** + * 直行标识 + */ + public static final String ROUTE_STRAIGHT = "直行"; + + /** + * 向右前方行驶标识 + */ + public static final String ROUTE_RIGHT_STRAIGHT = "向右前方行驶"; + + /** + * 向左前方行驶标识 + */ + public static final String ROUTE_LEFT_STRAIGHT = "向左前方行驶"; + + private Const() { + } +} \ No newline at end of file diff --git a/DistributedMapDemo/tinymap/src/main/java/com/dongyu/tinymap/util/ImageUtils.java b/DistributedMapDemo/tinymap/src/main/java/com/dongyu/tinymap/util/ImageUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..6d8ead1603763d62fe66d709572e4375f7a3cb0f --- /dev/null +++ b/DistributedMapDemo/tinymap/src/main/java/com/dongyu/tinymap/util/ImageUtils.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License,Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.dongyu.tinymap.util; + +import com.dongyu.tinymap.ResourceTable; + +import ohos.app.Context; +import ohos.global.resource.NotExistException; +import ohos.media.image.ImageSource; +import ohos.media.image.PixelMap; +import ohos.media.image.common.Size; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; + +/** + * MapHelper + * + * @since 2021-02-01 + */ +public class ImageUtils { + private static final String TAG = ImageUtils.class.getName(); + + private static final int TILE_LENGTH = 513; + + private static final int TIME_OUT = 5 * 1000; + + private static final int IMAGE_WIDTH_HEIGHT = 80; + + private ImageUtils() { + } + + /** + * 获取图像id + * + * @param actionType actionType + * @return imageId + */ + public static int getImageId(String actionType) { + int imageId = 0; + switch (actionType) { + case Const.ROUTE_STRAIGHT: + imageId = ResourceTable.Media_nav_straight; + break; + case Const.ROUTE_END: + imageId = ResourceTable.Media_route_end; + break; + case Const.ROUTE_START: + imageId = ResourceTable.Media_route_start; + break; + case Const.ROUTE_TURN_LEFT: + imageId = ResourceTable.Media_nav_turn_left; + break; + case Const.ROUTE_TURN_RIGHT: + imageId = ResourceTable.Media_nav_turn_right; + break; + case Const.ROUTE_LEFT_STRAIGHT: + imageId = ResourceTable.Media_nav_turn_little_left; + break; + case Const.ROUTE_RIGHT_STRAIGHT: + imageId = ResourceTable.Media_nav_turn_little_right; + break; + case Const.ROUTE_PEOPLE: + imageId = ResourceTable.Media_loc; + break; + default: + break; + } + return imageId; + } + + /** + * getPixelMap + * + * @param context context + * @param actionType actionType + * @return PixelMap + */ + public static PixelMap getPixelMap(Context context, String actionType) { + InputStream drawableInputStream = null; + PixelMap pixelMap = null; + try { + drawableInputStream = context.getResourceManager().getResource(ImageUtils.getImageId(actionType)); + ImageSource imageSource = ImageSource.create(drawableInputStream, new ImageSource.SourceOptions()); + ImageSource.DecodingOptions options = new ImageSource.DecodingOptions(); + options.desiredSize = new Size(IMAGE_WIDTH_HEIGHT, IMAGE_WIDTH_HEIGHT); + pixelMap = imageSource.createPixelmap(options); + return pixelMap; + } catch (IOException | NotExistException exception) { + LogUtils.info(TAG, "getPixelMap:" + exception.getMessage()); + } finally { + if (drawableInputStream != null) { + try { + drawableInputStream.close(); + } catch (IOException e) { + LogUtils.info(TAG, "getPixelMap:" + e.getMessage()); + } + } + } + return pixelMap; + } + + /** + * 从网络获取地图瓦片数据 + * + * @param urlString urlString + * @return PixelMap + */ + public static PixelMap getMapPixelMap(String urlString) { + InputStream is = null; + PixelMap pixelMap = null; + try { + URL url = new URL(urlString); + URLConnection con = url.openConnection(); + con.setConnectTimeout(TIME_OUT); + is = con.getInputStream(); + ImageSource source = ImageSource.create(is, new ImageSource.SourceOptions()); + ImageSource.DecodingOptions options = new ImageSource.DecodingOptions(); + options.desiredSize = new Size(TILE_LENGTH, TILE_LENGTH); + pixelMap = source.createPixelmap(options); + return pixelMap; + } catch (IOException exception) { + LogUtils.info(TAG, "getImagePixelMap:" + exception.getMessage()); + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException e) { + LogUtils.info(TAG, "getImagePixelMap:" + e.getMessage()); + } + } + } + return pixelMap; + } +} diff --git a/DistributedMapDemo/tinymap/src/main/java/com/dongyu/tinymap/util/LogUtils.java b/DistributedMapDemo/tinymap/src/main/java/com/dongyu/tinymap/util/LogUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..2c3da9a66ac3e27382300ebef7dd05b4bb9f4dd4 --- /dev/null +++ b/DistributedMapDemo/tinymap/src/main/java/com/dongyu/tinymap/util/LogUtils.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License,Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.dongyu.tinymap.util; + +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; + +/** + * LogUtils + * + * @since 2021-03-12 + */ +public class LogUtils { + private static final String TAG_LOG = "LogUtil"; + + private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0, LogUtils.TAG_LOG); + + private static final String LOG_FORMAT = "%{public}s: %{public}s"; + + private LogUtils() { + } + + /** + * 打印info日志 + * + * @param tag log tag + * @param msg log message + */ + public static void info(String tag, String msg) { + HiLog.info(LABEL_LOG, LOG_FORMAT, tag, msg); + } + + /** + * 打印error日志 + * + * @param tag log tag + * @param msg log message + */ + public static void error(String tag, String msg) { + HiLog.error(LABEL_LOG, LOG_FORMAT, tag, msg); + } +} diff --git a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/util/ScreenUtils.java b/DistributedMapDemo/tinymap/src/main/java/com/dongyu/tinymap/util/ScreenUtils.java similarity index 98% rename from DistributedMapDemo/entry/src/main/java/com/huawei/codelab/util/ScreenUtils.java rename to DistributedMapDemo/tinymap/src/main/java/com/dongyu/tinymap/util/ScreenUtils.java index 60ada4f4c1e332a0a82181655eead472f1f0e7d7..cd417792044dcf3ce75ef71a34b1826930a8e24b 100644 --- a/DistributedMapDemo/entry/src/main/java/com/huawei/codelab/util/ScreenUtils.java +++ b/DistributedMapDemo/tinymap/src/main/java/com/dongyu/tinymap/util/ScreenUtils.java @@ -13,7 +13,7 @@ * limitations under the License. */ -package com.huawei.codelab.util; +package com.dongyu.tinymap.util; import ohos.agp.utils.Point; import ohos.agp.window.service.Display; diff --git a/DistributedMapDemo/tinymap/src/main/resources/base/element/string.json b/DistributedMapDemo/tinymap/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..030d3671f7b48158ffb27908748ca903591a697d --- /dev/null +++ b/DistributedMapDemo/tinymap/src/main/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "tinymap_library", + "value": "tinymap_library" + } + ] +} diff --git a/DistributedMapDemo/tinymap/src/main/resources/base/media/loc.png b/DistributedMapDemo/tinymap/src/main/resources/base/media/loc.png new file mode 100644 index 0000000000000000000000000000000000000000..74ead4cdf5c1971d8880b4d2759e37f18adc476c Binary files /dev/null and b/DistributedMapDemo/tinymap/src/main/resources/base/media/loc.png differ diff --git a/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_straight.png b/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_straight.png new file mode 100644 index 0000000000000000000000000000000000000000..3aa37c27bf0f700b8077162b6007f555ea0cff48 Binary files /dev/null and b/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_straight.png differ diff --git a/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_turn_left.png b/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_turn_left.png new file mode 100644 index 0000000000000000000000000000000000000000..c9a2740e0e41c166e1086fc5d83f4f6feedeb699 Binary files /dev/null and b/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_turn_left.png differ diff --git a/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_turn_little_left.png b/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_turn_little_left.png new file mode 100644 index 0000000000000000000000000000000000000000..2b1f8bdd9668cafa05bd15d210957b0161d037ca Binary files /dev/null and b/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_turn_little_left.png differ diff --git a/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_turn_little_right.png b/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_turn_little_right.png new file mode 100644 index 0000000000000000000000000000000000000000..a86b74605cc914b6844237f9d8814717cae9c50b Binary files /dev/null and b/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_turn_little_right.png differ diff --git a/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_turn_right.png b/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_turn_right.png new file mode 100644 index 0000000000000000000000000000000000000000..5e896a829b2165bf0f0f638b78040a6fab0e4c12 Binary files /dev/null and b/DistributedMapDemo/tinymap/src/main/resources/base/media/nav_turn_right.png differ diff --git a/DistributedMapDemo/tinymap/src/main/resources/base/media/route_end.png b/DistributedMapDemo/tinymap/src/main/resources/base/media/route_end.png new file mode 100644 index 0000000000000000000000000000000000000000..1522c6825fe4ea80016bb88e111c5890c5dbbd92 Binary files /dev/null and b/DistributedMapDemo/tinymap/src/main/resources/base/media/route_end.png differ diff --git a/DistributedMapDemo/tinymap/src/main/resources/base/media/route_start.png b/DistributedMapDemo/tinymap/src/main/resources/base/media/route_start.png new file mode 100644 index 0000000000000000000000000000000000000000..9bf16b9750174019b511a313ecc6e3a62f16a5d1 Binary files /dev/null and b/DistributedMapDemo/tinymap/src/main/resources/base/media/route_start.png differ