SpringBoot整合微信小程序(二)获取地理位置,MySql存储

1、微信小程序获取GeometryJSON格式的地理位置

1.1、获取用户授权

在app.json中加入地理位置授权

在这里插入图片描述

1.2、刷新地理位置工具js

获取地理位置,参照一片博客,单独写了一个工具js
module.exports = {
  refreshUserLocation: refreshUserLocation,
  getLocation:getLocation
}

function refreshUserLocation(callback) {
  wx.getSetting({
      success: (res) => {
          // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
          // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
          // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
          // 拒绝授权后再次进入重新授权
          if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
              // console.log('authSetting:status:拒绝授权后再次进入重新授权', res.authSetting['scope.userLocation'])
              wx.showModal({
                  title: '',
                  content: '需要获取你的地理位置,请确认授权',
                  success: res=> {
                      if (res.cancel) {
                          wx.showToast({
                              title: '拒绝授权',
                              icon: 'none'
                          })
                          setTimeout(() => {
                              wx.navigateBack()
                          }, 1500)
                      } else if (res.confirm) {
                          wx.openSetting({
                              success: function (dataAu) {
                                  // console.log('dataAu:success', dataAu)
                                  if (dataAu.authSetting["scope.userLocation"] == true) {
                                      //再次授权,调用wx.getLocation的API
                                      this.getLocation(dataAu,callback)
                                  } else {
                                      wx.showToast({
                                          title: '授权失败',
                                          icon: 'none'
                                      })
                                      setTimeout(() => {
                                          wx.navigateBack()
                                      }, 1500)
                                  }
                              }
                          })
                      }
                  }
              })
          }
          // 初始化进入,未授权
          else if (res.authSetting['scope.userLocation'] == undefined) {
              // console.log('authSetting:status:初始化进入,未授权', 			res.authSetting['scope.userLocation'])
              //调用wx.getLocation的API
              this.getLocation(res,callback)
          }
          // 已授权
          else if (res.authSetting['scope.userLocation']) {
              // console.log('authSetting:status:已授权', res.authSetting['scope.userLocation'])
              //调用wx.getLocation的API
              this.getLocation(res,callback)
          }
      }
  })
}

// 微信获得经纬度
function getLocation(userLocation,callback) {
  wx.getLocation({
      type: "wgs84",
      success: res=> {
           //按格式返回位置坐标信息
          var location = {
            type:"Point",
            coordinates:[
              res.longitude,
              res.latitude
            ]
          }
          callback(location)
      },
      fail: function (res) {
          // console.log('getLocation:fail', res)
          if (res.errMsg === 'getLocation:fail:auth denied') {
              wx.showToast({
                  title: '拒绝授权',
                  icon: 'none'
              })
              setTimeout(() => {
                  wx.navigateBack()
              }, 1500)
              return
          }
          if (!userLocation || !userLocation.authSetting['scope.userLocation']) {
              vm.getUserLocation()
          } else if (userLocation.authSetting['scope.userLocation']) {
              wx.showModal({
                  title: '',
                  content: '请在系统设置中打开定位服务',
                  showCancel: false,
                  success: result => {
                      if (result.confirm) {
                          wx.navigateBack()
                      }
                  }
              })
          } else {
              wx.showToast({
                  title: '授权失败',
                  icon: 'none'
              })
              setTimeout(() => {
                  wx.navigateBack()
              }, 1500)
          }
      }
  })
}

1.3、获取地理位置,发起后端请求

loactionDemo(location) {
   //像后端传入地理位置
   api.get('/demo/location', {
     location: JSON.stringify(location)//转json字符串
   }).then(result => {
   	
   }
}

2、SpringBoot接收地理位置并存储到MySql

2.1、pom.xml加入相关依赖坐标

<dependency>
	<groupId>org.geotools</groupId>
	<artifactId>gt-geojson</artifactId>
	<version>17.1</version>
</dependency>

<dependency>
	<groupId>com.vividsolutions</groupId>
	<artifactId>jts</artifactId>
	<version>1.13</version>
</dependency>

2.2、实体注解中注明是point类型

@Column(columnDefinition = "point")
private Point location;//位置地理信息

2.3、GeoJSONUtil工具类

public class GeoJSONUtil {

	Point类型转geoJSON格式字符串
	public static String getGeoJSON(Point geometry){

		if(geometry==null){
			return null;
		}
		StringWriter writer = new StringWriter();
		GeometryJSON g = new GeometryJSON();
		try {
			g.write(geometry, writer);
		} catch (IOException e) {
			e.printStackTrace();
		}

		String json = writer.toString();
		if("null".equals(json)){
			json = null;
		}
		return json;
	}
	//geoJSON格式字符串转Point类型
	public static Point getGeometryFromGeoJSON(String geoJSON){

		if(StringUtils.isEmpty(geoJSON)){
			return null;
		}

		GeometryJSON  g = new GeometryJSON();

		Point geometry =null ;

		try {

			geometry=(Point)g.read(geoJSON);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		return geometry;
	}

	//数据库AsText查询出来的wkt格式的字符串转为geoJSON返回到前端
	public static String getGeoJSONFromWKT(String geoWkt){

		if(StringUtils.isEmpty(geoWkt)){
			return null;
		}
		WKTReader reader = new WKTReader();

		String ret = null;
		try {
			Geometry geometry = reader.read(geoWkt);
			StringWriter writer = new StringWriter();
			GeometryJSON g = new GeometryJSON();
			g.write(geometry, writer);
			ret = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;

	}

}

2.4原生sql根据位置查询排序

public List<Map> findBuildingByLocation(String locationPointStr, String buildingName){

	StringBuilder sql=new StringBuilder();
	sql.append(" select b.*,AsText(b.location) as locationText,ST_DISTANCE_SPHERE(b.location,:location) as distance from buildings b where b.del_flag=0 ");
	if(StringUtils.isNotEmpty(buildingName)){
	    sql.append(" and b.building_name like :building_name ");
	}
	sql.append(" order by distance");
	
	Query query = entityManager.createNativeQuery(sql.toString());
	query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
	query.setParameter("location",GeoJSONUtil.getGeometryFromGeoJSON(locationPoint));
	query.setFirstResult(0);
	query.setMaxResults(10);
	if(StringUtils.isNotEmpty(buildingName)){
	    query.setParameter("building_name","%"+buildingName+"%");
	}
	
	List<Map> mapList=query.getResultList();
	
	return mapList;
	
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值