Skip to content

Instantly share code, notes, and snippets.

@yiichou
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yiichou/ab3970341008b04a788c to your computer and use it in GitHub Desktop.
Save yiichou/ab3970341008b04a788c to your computer and use it in GitHub Desktop.
计算成都市两地间车程在三环内外的分布(片段)
get_distance = ->
map = new BMap.Map('allmap')
map.centerAndZoom(new BMap.Point(104.072, 30.663), 13)
old_ads = ... # 地点1的坐标
new_ads = ... # 地点2的坐标
old_point = new BMap.Point(old_ads[x],old_ads[y])
new_point = new BMap.Point(new_ads[x],new_ads[y])
get_ratio = (point1,point2) ->
# 根据球面坐标获得平面坐
get_mecator = (poi) ->
map.getMapType().getProjection().lngLatToPoint(poi)
# 判断点是否在三环内
point_in_circle = (pot) ->
res = (pot.x-dot.x)*(pot.x-dot.x) + (pot.y-dot.y)*(pot.y-dot.y) - r*r
if res > 0
false
else
true
# 当两地跨域三环时,获取三环外车程比例
get_cross_rat = (x, x2) ->
x ||= x2
if point_in_circle(pot1)
rat = Math.abs(pot2.x - x) / Math.abs(pot1.x - pot2.x)
else
rat = Math.abs(pot1.x - x) / Math.abs(pot1.x - pot2.x)
rat
# 原点设置为 天府广场地铁站
# 球面坐标 104.072486, 30.66348
# 平面坐标(百度) 11585422.2, 3567130.97
# 计算方式 dot = get_mecator(new BMap.Point(104.072486, 30.66348))
# 半径设置为 9300
r = 9300.0
dot = x: 11585422.2, y: 3567130.97
pot1 = get_mecator(point1)
pot2 = get_mecator(point2)
# 两点直线方程 y=kx+d
k = (pot2.y - pot1.y) / (pot2.x - pot1.x)
d = pot1.y - k * pot1.x
# 直线与园切点方程 ax2+bx+c=0
a = 1 + k * k
b = 2 * (k * d - k * dot.y - dot.x)
c = dot.x * dot.x + dot.y * dot.y + d * d - 2 * dot.y * d - r * r
det = b * b - 4 * a * c
if det < 0
# console.log('无解')
x1 = null
x2 = null
else
x1 = (Math.sqrt(det) - b) / (2*a)
x2 = (0 - Math.sqrt(det) - b) / (2*a)
if (x1-pot1.x)*(x1-pot2.x) > 0
# console.log('x1无用根')
x1 = null
if (x2-pot1.x)*(x2-pot2.x) > 0
# console.log('x2无用根')
x2 = null
if x1? && x2? # 两点都在三环外,内切三环
rat = 1 - ( (x1 - x2) / Math.abs(pot1.x - pot2.x) )
else if x1? || x2? # 跨越三环
rat = get_cross_rat(x1, x2)
else # 都在三环内 或 都在三环外但不过三环
rat = `point_in_circle(pot1) ? 0 : 1`
# console.log('rat='+rat)
rat
rat = get_ratio(old_point,new_point)
transit = new BMap.DrivingRoute(map, {
onSearchComplete: (results) ->
# console.log(results.getPlan(0))
if transit.getStatus() != BMAP_STATUS_SUCCESS
return
distance = results.getPlan(0).getDistance(false) / 1000
distance_out = Math.ceil( distance * rat )
distance_in = Math.round( distance * (1 - rat) )
distances = [distance_in, distance_out]
# save distances # distances便是结果
});
transit.search(old_point,new_point)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment