geronimod / mormon

OSM Routing in Ruby, based on pyroutelib2
MIT License
23 stars 6 forks source link

Getting node_start, node_end #7

Closed a0s closed 5 years ago

a0s commented 5 years ago

Hi, I am wondering how to get node_start/node_end if I have lan/lng of points only? Should I use some additional gem or service?

geronimod commented 5 years ago

Hi there, has been long time since the last time i used this gem. Taking a look at the OSM loader, you should have read access to the nodes loaded, i think you can do something like:

start_node = osm_loader.nodes.find { |lat, lon| start_lat == lat && start_lon == lon }

where start_lat and start_lon are what you have, write a similar line of code to find the end_node, then you will have the node_id doing start_node[:id].

Let me know if that works for you.

a0s commented 5 years ago

Brilliant! It works! At least it looks like :)

                 user     system      total        real
osm_loader:Loading from cache /Users/a0s/map/cache/Moscow.osm.pstore...
             84.175139   5.060020  89.235159 ( 89.905210)
osm_loader:  0.000032   0.000003   0.000035 (  0.000034)
start_node:  0.014644   0.000620   0.015264 (  0.015288)
end_node:    0.020978   0.001070   0.022048 (  0.022086)
find_route:  0.126352   0.004823   0.131175 (  0.131449)
["success",
 [[55.8020036, 37.5139011],
....
a0s commented 5 years ago
require 'mormon'
require 'pp'
require 'benchmark'

start_lat, start_lon = [55.802754, 37.514695]
end_lat, end_lon = [55.804722, 37.633787]

osm_loader = nil
osm_router = nil
start_node_id = nil
end_node_id = nil
result = nil
eps = 0.001

Benchmark.bm(10) do |x|
  x.report('osm_loader:') do
    map_path = File.expand_path(File.join(__FILE__, %w(.. Moscow.osm)))
    cache_dir = File.join File.dirname(__FILE__), "cache"
    Mormon::OSM::Loader.cache_dir = cache_dir
    osm_loader = Mormon::OSM::Loader.new map_path, cache: true
  end

  x.report('osm_loader:') do
    osm_router = Mormon::OSM::Router.new osm_loader
  end

  x.report('start_node:') do
    start_node_id, _ = osm_loader.nodes.find { |_, h| (start_lat - h[:lat]).abs < eps && (start_lon - h[:lon]).abs < eps }
  end

  puts "start_node_id=#{start_node_id}"

  x.report('end_node:') do
    end_node_id, _ = osm_loader.nodes.find { |_, h| (end_lat - h[:lat]).abs < eps && (end_lon - h[:lon]).abs < eps }
  end

  puts "end_node_id=#{end_node_id}"

  x.report('find_route:') do
    result = osm_router.find_route start_node_id, end_node_id, :car
  end
end

pp result