EC20 GPS模块 百度地图

就是想显示出来接收器当前的位置,后端是一个树莓派,使用串口和EC20通讯获取GPS数据。

<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<style type="text/css">
		body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
	</style>
	<script type="text/javascript" src="//api.map.baidu.com/api?type=webgl&v=1.0&ak=【API_KEY】"></script>
	<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
	<title>地图展示</title>
</head>
<body>
	<div id="allmap"></div>
</body>
</html>
<script type="text/javascript">
	// 百度地图API功能-Init
	var map = new BMapGL.Map("allmap");
	$.getJSON('http://192.168.1.106:8888/gps', function(data){
				var point = new BMapGL.Point(data.longi, data.lati);
				map.centerAndZoom(point, 15);
				});

	function refresh_gps(){
		$.getJSON('http://192.168.1.106:8888/gps', function(data){
			console.log(data);
			var json = data;
			// 创建小车图标
			var pt = new BMapGL.Point(json.longi, json.lati);
			var myIcon = new BMapGL.Icon("car.png", new BMapGL.Size(40, 20));
			var marker = new BMapGL.Marker(pt, {icon: myIcon});  // 创建标注
			map.addOverlay(marker);              // 将标注添加到地图中
	    })
		var httpRequest = new XMLHttpRequest();//第一步:创建需要的对象
		httpRequest.open('POST', '', true); //第二步:打开连接/***发送json格式文件必须设置请求头 ;如下 - */
		httpRequest.setRequestHeader("Content-type","application/json");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
		
		//var obj = { gps: 1 };
		//httpRequest.send(JSON.stringify(obj));//发送请求 将json写入send中
		httpRequest.send();
		httpRequest.onreadystatechange = function () {//请求后的回调接口,可将请求成功后要执行的程序写在其中
			if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
				
				}
		};

	}
	
	setInterval(refresh_gps, 1000);

</script>

再放一个标志图在IIS目录下

这里有个问题,EC20直接出来的坐标并不是百度地图的坐标,两个的体系标准不一样。需要在使用百度地图的API去进行坐标转换。随便写了一个小程序,使用python使用串口通讯,获取GPS信息。同时也是一个简易的com terminal

from flask import request, Flask, jsonify, Response

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False


@app.route('/gps', methods=['GET'])
def post_Data():
    global lati, longi
    recognize_info = {"lati": lati, "longi": longi}
    headers = {'Access-Control-Allow-Origin': '*'}
    return jsonify(recognize_info), 200, headers    


# -*- coding:utf-8 -*-
import serial
import time
import threading
import sys
import re
import requests
import json

SERIAL_COMMAND = "/dev/ttyUSB2"
SERIAL_GPSDATA = "/dev/ttyUSB1"


ser_cmd = serial.Serial(SERIAL_COMMAND, 115200)
ser_gps = serial.Serial(SERIAL_GPSDATA, 115200)

ser_cmd.flushInput()
ser_gps.flushInput()

def main_recv_cmd():
	while True:
		count = ser_cmd.inWaiting()  # 位置4
		if count != 0:
			recv = ser_cmd.read(count)  # 位置5
			print(recv)
			ser_cmd.flushInput()
		time.sleep(0.1)  # 位置8

def main_recv_gps():
	while True:
		count = ser_gps.inWaiting()  # 位置4
		if count != 0:
			recv = ser_gps.read(count)  # 位置5
			result = re.findall(r"\$GPGGA,.*\r\n", recv.decode('ascii'))		  # only show GPGGA
			if len(result) != 0:
				result = result[0]
				result = result.split(',')
				if len(result[2]) != 0:
					global lati, longi
					_lati = int(result[2][:2]) + float(result[2][2:]) / 60
					_longi = int(result[4][:3]) + float(result[4][3:]) / 60
					_lati = _lati if "N" in result[3] else _lati * -1
					_longi = _longi if "E" in result[5] else _longi * -1
					print("[Raw] - 纬度:%s , 经度:%s , 可用卫星数:%s" % (_lati, _longi, result[7]))
					try:
						r = requests.get(url="http://api.map.baidu.com/geoconv/v1/?coords=%s,%s&from=1&to=5&ak=【API_KEY】" % (_longi, _lati))
						xy = json.loads(r.content.decode('utf-8'))["result"][0]
						print("[Baidu] - 纬度:%s , 经度:%s" % (xy["y"], xy["x"]))
						lati, longi = xy["y"], xy["x"]
					except:
						print("Convert to Baidu Coordination failed! Check the Internet connection!")
						pass
				else:
					print("正在搜星定位,三分钟内无法定位请检查天线...")
			else:
				print("Something went odd.")
			ser_gps.flushInput()
		time.sleep(0.1)  # 位置8


def main_send():
	while True:
		command = input()
		command = command.encode('ascii') + b'\r\n'
		ser_cmd.write(command)

if __name__ == '__main__':
	th1 = threading.Thread(target=main_recv_cmd)
	th1.start()
	th3 = threading.Thread(target=main_recv_gps)
	th3.start()
	th2 = threading.Thread(target=main_send)
	th2.start()

	lati, longi = 0, 0
	app.run(debug=False, host='0.0.0.0', port=8888)

	th1.join()
	th2.join()
	th3.join()
	print("Terminated!")

结果图:

如果不更换坐标系,会偏差一公里左右。 

おすすめ

転載: blog.csdn.net/uiop_uiop_uiop/article/details/108175140