Browse Source

Add 使用百度地图服务计算配送时间和配送距离

enilu 6 years ago
parent
commit
fd93af3334

+ 7 - 0
flash-waimai-api/src/main/java/cn/enilu/flash/api/controller/business/CartController.java

@@ -5,6 +5,7 @@ import cn.enilu.flash.bean.entity.front.*;
 import cn.enilu.flash.bean.vo.front.Rets;
 import cn.enilu.flash.dao.MongoRepository;
 import cn.enilu.flash.service.front.IdsService;
+import cn.enilu.flash.service.front.PositionService;
 import cn.enilu.flash.utils.Lists;
 import cn.enilu.flash.utils.Maps;
 import org.nutz.json.Json;
@@ -27,6 +28,9 @@ public class CartController extends BaseController {
     private MongoRepository mongoRepository;
     @Autowired
     private IdsService idsService;
+    @Autowired
+    private PositionService positionService;
+
     @RequestMapping(value = "/v1/carts/checkout",method = RequestMethod.POST)
     public Object checkout(HttpServletRequest request){
 
@@ -38,6 +42,9 @@ public class CartController extends BaseController {
         List<Payment> paymentList = mongoRepository.findAll(Payment.class);
         Shop shop = mongoRepository.findOne(Shop.class,restaurantId);
         String to =  shop.getLatitude()+","+shop.getLongitude();
+        Map distance = positionService.getDistance(from,to);
+        String deliver_time = distance!=null?distance.get("duration").toString():"";
+        carts.setDelivery_reach_time(deliver_time);
         carts.setId(idsService.getId(Ids.CART_ID));
         carts.setPayments(paymentList);
         carts.setSig(String.valueOf(Math.ceil(Math.random()*1000000)));

+ 12 - 6
flash-waimai-api/src/main/java/cn/enilu/flash/api/controller/business/PositionController.java

@@ -1,6 +1,7 @@
 package cn.enilu.flash.api.controller.business;
 
 import cn.enilu.flash.api.controller.BaseController;
+import cn.enilu.flash.bean.vo.business.City;
 import cn.enilu.flash.bean.vo.business.CityInfo;
 import cn.enilu.flash.bean.vo.front.Rets;
 import cn.enilu.flash.dao.MongoRepository;
@@ -9,8 +10,6 @@ import com.google.common.base.Strings;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
-import ch.qos.logback.classic.Logger;
-
 import javax.servlet.http.HttpServletRequest;
 import java.util.Map;
 
@@ -28,7 +27,6 @@ public class PositionController extends BaseController {
     private PositionService positionService;
 
     @RequestMapping(value = "/v1/cities",method = RequestMethod.GET)
-
     public Object cities(@RequestParam("type") String type, HttpServletRequest request) {
         Map cities = mongoRepository.findOne("cities");
         Map data = (Map) cities.get("data");
@@ -64,10 +62,18 @@ public class PositionController extends BaseController {
 
     @RequestMapping(value = "/v1/pois",method = RequestMethod.GET)
     public Object getPoiByCityAndKeyword(@RequestParam(value = "type",defaultValue = "search")String type,
-                       @RequestParam(value = "city_id")Integer cityId,
+                       @RequestParam(value = "city_id",required = false)Integer cityId,
                        @RequestParam(value = "keyword")String keyword){
-        Map map =   positionService.findById(cityId);
-        return Rets.success(positionService.searchPlace(map.get("name").toString(),keyword));
+        String cityName = null;
+        if(cityId==null){
+            City city = positionService.guessCity(getIp());
+            cityName = city.getName();
+        }else {
+            Map map = positionService.findById(cityId);
+            cityName = map.get("name").toString();
+        }
+        return Rets.success(positionService.searchPlace(cityName, keyword));
+
     }
 
     @RequestMapping(value = "/v1/position/pois",method = RequestMethod.GET)

+ 3 - 2
flash-waimai-api/src/main/resources/application-dev.properties

@@ -20,5 +20,6 @@ cfg.tencentkey=RLHBZ-WMPRP-Q3JDS-V2IQA-JNRFH-EJBHL
 cfg.tencentkey2=RRXBZ-WC6KF-ZQSJT-N2QU7-T5QIT-6KF5X
 cfg.tencentkey3=OHTBZ-7IFRG-JG2QF-IHFUK-XTTK6-VXFBN
 
-cfg.baidukey=fjke3YUipM9N64GdOIh1DNeK2APO2WcT
-cfg.baidukey2=fjke3YUipM9N64GdOIh1DNeK2APO2WcT
+cfg.baidu.map.url=http://api.map.baidu.com/
+cfg.baidu.key=fjke3YUipM9N64GdOIh1DNeK2APO2WcT
+cfg.baidu.key2=fjke3YUipM9N64GdOIh1DNeK2APO2WcT

+ 8 - 2
flash-waimai-core/src/main/java/cn/enilu/flash/bean/AppConfiguration.java

@@ -13,13 +13,19 @@ import org.springframework.stereotype.Component;
 @Data
 public class AppConfiguration {
     @Value("${api.qq.map.url}")
-    private String apiUrl;
+    private String qqApiUrl;
     @Value("${cfg.tencentkey}")
     private String tencentKey;
     @Value("${cfg.tencentkey2}")
     private String tencentKey2;
     @Value("${cfg.tencentkey3}")
-    private String tencentKey3;    
+    private String tencentKey3;
+    @Value("${cfg.baidu.map.url}")
+    private String baiduApiUrl;
+    @Value(("${cfg.baidu.key}"))
+    private String baiduKey;
+    @Value(("${cfg.baidu.key2}"))
+    private String baiduKey2;
     @Value("${img.dir}")
     private String imgDir;
 

+ 16 - 0
flash-waimai-core/src/main/java/cn/enilu/flash/bean/vo/business/City.java

@@ -0,0 +1,16 @@
+package cn.enilu.flash.bean.vo.business;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * @author :enilu
+ * @date :Created in 2019/10/23 22:06
+ */
+@Data
+public class City implements Serializable {
+    private Integer id;
+    private String name;
+    
+}

+ 51 - 8
flash-waimai-core/src/main/java/cn/enilu/flash/service/front/PositionService.java

@@ -2,10 +2,11 @@ package cn.enilu.flash.service.front;
 
 import cn.enilu.flash.bean.AppConfiguration;
 import cn.enilu.flash.bean.constant.cache.Cache;
+import cn.enilu.flash.bean.vo.business.City;
 import cn.enilu.flash.bean.vo.business.CityInfo;
 import cn.enilu.flash.dao.MongoRepository;
 import cn.enilu.flash.utils.HttpClients;
-import com.google.common.collect.Maps;
+import cn.enilu.flash.utils.Maps;
 import org.nutz.json.Json;
 import org.nutz.mapl.Mapl;
 import org.slf4j.Logger;
@@ -31,7 +32,25 @@ public class PositionService {
     private AppConfiguration appConfiguration;
     @Autowired
     private MongoRepository mongoRepository;
-    @Cacheable(value = Cache.APPLICATION ,key = "#root.targetClass.simpleName+':'+#ip")
+
+    /**
+     * 根据ip获取所属城市id和名称
+     * @param ip
+     * @return
+     */
+    @Cacheable(value = Cache.APPLICATION ,key = "#root.targetClass.simpleName+':guess_city:'+#ip")
+    public City guessCity(String ip){
+        CityInfo cityInfo = getPostion(ip);
+        if(cityInfo!=null) {
+            Map map = findByName(cityInfo.getCity());
+            City city = new City();
+            city.setId(Integer.valueOf(map.get("id").toString()));
+            city.setName(map.get("name").toString());
+            return city;
+        }
+        return null;
+    }
+    @Cacheable(value = Cache.APPLICATION ,key = "#root.targetClass.simpleName+':position:'+#ip")
     public CityInfo getPostion(String ip) {
         logger.info("根据ip:{}获取城市信息",ip);
         Map<String, String> map = Maps.newHashMap();
@@ -39,7 +58,7 @@ public class PositionService {
         map.put("key", appConfiguration.getTencentKey());
         Map result = null;
         try {
-            String str = HttpClients.get(appConfiguration.getApiUrl() + "location/v1/ip", map);
+            String str = HttpClients.get(appConfiguration.getQqApiUrl() + "location/v1/ip", map);
             result = (Map) Json.fromJson(str);
         } catch (Exception e) {
             logger.error("获取地理位置异常", e);
@@ -47,7 +66,7 @@ public class PositionService {
         if (result == null || Integer.valueOf(result.get("status").toString()) != 0) {
             try {
                 map.put("key", appConfiguration.getTencentKey2());
-                String str = HttpClients.get(appConfiguration.getApiUrl() + "location/v1/ip", map);
+                String str = HttpClients.get(appConfiguration.getQqApiUrl() + "location/v1/ip", map);
                 result = (Map) Json.fromJson(str);
             } catch (Exception e) {
                 logger.error("获取地理位置异常", e);
@@ -56,7 +75,7 @@ public class PositionService {
         if (result == null || Integer.valueOf(result.get("status").toString()) != 0) {
             try {
                 map.put("key", appConfiguration.getTencentKey3());
-                String str = HttpClients.get(appConfiguration.getApiUrl() + "location/v1/ip", map);
+                String str = HttpClients.get(appConfiguration.getQqApiUrl() + "location/v1/ip", map);
                 result = (Map) Json.fromJson(str);
             } catch (Exception e) {
                 logger.error("获取地理位置异常", e);
@@ -88,7 +107,7 @@ public class PositionService {
         params.put("boundary", "region(" + URLEncoder.encode(cityName) + ",0)");
         params.put("page_size", "10");
         try {
-            String str = HttpClients.get(appConfiguration.getApiUrl() + "place/v1/search", params);
+            String str = HttpClients.get(appConfiguration.getQqApiUrl() + "place/v1/search", params);
             Map result = (Map) Json.fromJson(str);
             if (Integer.valueOf(result.get("status").toString()).intValue() == 0) {
                 return (List) result.get("data");
@@ -149,7 +168,7 @@ public class PositionService {
         map.put("key", appConfiguration.getTencentKey());
         Map result = Maps.newHashMap();
         try {
-            String str = HttpClients.get(appConfiguration.getApiUrl() + "geocoder/v1", map);
+            String str = HttpClients.get(appConfiguration.getQqApiUrl() + "geocoder/v1", map);
             Map response = (Map) Json.fromJson(str);
             if ("0".equals(response.get("status").toString())) {
                 result.put("address", Mapl.cell(response,"result.address"));
@@ -167,7 +186,31 @@ public class PositionService {
         return result;
     }
 
-    public void getDistance(String from,String to){
+    public Map<String,String> getDistance(String from,String to){
+        Map<String,String> params = Maps.newHashMap(
+                "ak",appConfiguration.getBaiduKey(),
+                "output","json",
+                "origins",from,
+                "destinations",to
+        );
+        try {
+            //使用百度地图api获取距离值:
+            //routematrix/v2/riding 骑行
+            //routematrix/v2/driving 开车
+            //routematrix/v2/walking 步行
+            String str = HttpClients.get(appConfiguration.getBaiduApiUrl() + "routematrix/v2/riding", params);
+            Map response = (Map) Json.fromJson(str);
+            if("0".equals(response.get("status").toString())){
+              Map result =  Maps.newHashMap(
+                      "distance",Mapl.cell(response,"result[0].distance.text"),
+                      "duration",Mapl.cell(response,"result[0].duration.text")
+              );
+              return result;
+            }
 
+        }catch (Exception e){
+            logger.error("通过百度获取配送距离失败",e);
+        }
+        return null;
     }
 }