dezhou_client/lua_probject/base_project/Game/Data/Location.lua

84 lines
1.9 KiB
Lua

-- Edit By ChenGY
-- 记录玩家位置,距离计算
Location = {
longitude = 0,
latitude = 0,
default = true,
address = nil,
}
local M = Location
function M.new(str)
local self = {}
setmetatable(self, {__index = M})
self:LoadLocation(str)
if str and str ~= "" then
self.default = false
else
self.default = true
end
return self
end
-- 获取详细地址
function M:GetAddress(obj)
if self.address then
obj.text = self.address
else
coroutine.start(self.DownloadAddressInfo, self, obj)
end
end
function M:DownloadAddressInfo(obj)
-- bd09ll gcj02 wgs84ll
local coordtype = "&coordtype=wgs84ll"
-- if Application.platform == RuntimePlatform.Android then
-- coordtype = ""
-- end
local url = string.format("http://api.map.baidu.com/geocoder/v2/?ak=Z6qXIddQtwO8xaKunX4CURbwcV0GLSrG&location=%s,%s&output=json%s", self.latitude, self.longitude, coordtype)
local www = UnityEngine.WWW(url)
coroutine.www(www)
if string.utf8len(www.error) == 0 then
local txt = www.text
local json_add = json.decode(txt)
self.address = json_add.result.formatted_address
obj.text = self.address
end
end
-- 计算距离
function M:CalcDistance(loc)
local EARTH_RADIUS = 6378.137
local radLat1 = math.rad(self.latitude)
local radLat2 = math.rad(loc.latitude)
local a = radLat1 - radLat2
local b = math.rad(self.longitude) - math.rad(loc.longitude)
local s = 2 * math.asin(math.sqrt(math.pow(math.sin(a/2),2) + math.cos(radLat1)*math.cos(radLat2)*math.pow(math.sin(b/2),2)))
s = s * EARTH_RADIUS
local dist = math.floor(s * 10000 +.5) / 10000
return dist
end
function M:Location2String()
if self.default then return "" end
local str = self.longitude .. "," .. self.latitude
return str
end
function M:String2Location()
local loc = string.split(str, ",")
return loc
end
function M:LoadLocation(str)
local loc = string.split(str, ",")
self.longitude = tonumber(loc[1])
self.latitude = tonumber(loc[2])
end
return M