A
A
akyl-kb2018-03-15 12:48:55
OpenStreetMap
akyl-kb, 2018-03-15 12:48:55

How to calculate the total number of KM roads in the area?

How to calculate the total number of KM roads in a district, street or in a selected zone? Through a Google map, Yandex, etc.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
freeExec, 2018-03-15
@freeExec

1) Download the download of your region from gislab
2) Load them into the database using osm2pgsql
3) Calculate the lengths in the ST_Length projection of your choice

E
Eugene, 2018-03-15
@evgen9586

Specify how. From your point to a certain moment. Or where.
On the shortest path on foot or by car.
The GoogleMaps API is quite flexible and has a lot of options
if from your point to any point.

Determining your location
function myplace()
    {
        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                geocoding(position.coords.latitude, position.coords.longitude);
            });
        } else
        {
            console.log("Geolocation API не поддерживается в вашем браузере");
        }
    }

+ I did the conversion of Coordinates to an address
transformation
function geocoding(lat, lon)
    {
        var my_adress;
        var api_key = 'AIzaSyAsuS1MqzRBzRv1HRrfrlyoMRlkrVXEx0g';
        var cordinats = [lat,  lon];
        var loctype = 'ROOFTOP';
        var restype = 'street_address';
        var position = cordinats.join(",");
        var data = {latlng: position, location_type: loctype, result_type: restype, key: api_key};
        $.ajax({
            method: "GET",
            url: "https://maps.googleapis.com/maps/api/geocode/json",
            data: data,
            dataType: 'json',
            success: function (result) {
                console.log(result);
                my_adress = result.results[0].formatted_address;
                my_coords = result.results[0].geometry.location;

                alert("Вы здесь" + " " + "<" + " " + my_adress + " " + ">");
                initMap(my_coords,lat,lon);
            },
            error: function (err) {
                console.log("Ошибка сервера")
            }
        })
    }

Don't forget to call the definition function.
Now drawing the map, calculating the distance
Map
function initMap(coords,lat,lon){
        var latlng = new google.maps.LatLng(lat, lon);
        var map;
        var image = 'images/23.png';
        var basemarker = [

            [53.9143142,27.4173581],
            [53.9251061,27.5888264],
            [53.861006, 27.5692355],
            [53.9098637,27.5348443],
            [53.9351309,27.6492208]
        ];
        //style map
        var mapOptions = {
            center: latlng,
            zoom: 10,
            mapTypeControl: false,
            streetViewControl: false,
            styles: [{"featureType":"water","stylers":[{"saturation":43},{"lightness":-11},{"hue":"#0088ff"}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"hue":"#ff0000"},{"saturation":-100},{"lightness":99}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"color":"#808080"},{"lightness":54}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#ece2d9"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"color":"#ccdca1"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#767676"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","stylers":[{"visibility":"off"}]},{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#b8cb93"}]},{"featureType":"poi.park","stylers":[{"visibility":"on"}]},{"featureType":"poi.sports_complex","stylers":[{"visibility":"on"}]},{"featureType":"poi.medical","stylers":[{"visibility":"on"}]},{"featureType":"poi.business","stylers":[{"visibility":"simplified"}]}]
        };

        map = new google.maps.Map(document.getElementById('map'), mapOptions);

        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title:"Вы находитесь в данном месте"
        });
        for (var i = 0; i < basemarker.length; i++) { // отрисовка маркеров на карте
            var dbmarker= basemarker[i];
            var marker1 = new google.maps.Marker({
                position: {lat: dbmarker[0], lng: dbmarker[1]},
                map: map,
                icon:image,
                title: dbmarker[0],

            });
        }


    //отображение маршрута
        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer({
            draggable: true,
            map: map,
            panel: document.getElementById('right-panel')
        });


        var closestPointIdx = 0;
        var predict = 0;
        var dist = 0;
        var minDist = 100000;
        for (var i = 0 ; i < basemarker.length; i++) {
            console.log("Переменная",coords);
            var request = {
                origin:   {
                    // "LatLng":

                    "lat" : coords.lat,//координаты начальной точки
                    "lng" : coords.lng,//координаты начальной точки
                },

                destination:{
                    "lat" : basemarker[i][0],//координаты конечной точки
                    "lng" : basemarker[i][1]//координаты конечной точки
                },
                travelMode: 'DRIVING'
            };
            directionsService.route(request, function(response, status) {
                if (status == 'OK') {
                    dist = computeTotalDistance_crutch(response); //ответ отсюда  в массив, находим самое меньшее

                    if  (dist < minDist ) {
                        minDist = dist;

                        closestPointIdx = predict;
                        predict++;
                    }

                    displayRoute(latlng,{lat: basemarker[closestPointIdx][0], lng: basemarker[closestPointIdx][1]} , directionsService,
                        directionsDisplay,dist);



                }
            });

        }
    }
    function displayRoute(origin, destination, service, display) {

        service.route({
            origin: origin,
            destination: destination,

            travelMode: 'DRIVING',
            avoidTolls: true
        }, function(response, status) {
            if (status === 'OK') {
                display.setDirections(response);
            } else {
                console.log('Could not display directions due to: ' + status);
            }
        });
    }

    //Подсчёт расстояния

    function computeTotalDistance_crutch(result) {
        var total = 0;
        var myroute = result.routes[0];
        for (var i = 0; i < myroute.legs.length; i++) {
            total += myroute.legs[i].distance.value;
        }
        total = total / 1000;
        return total;
    }


    function viewRoute()
    {
        $("#right-panel").fadeIn(1000)
    }

The map has a property when displaying the route. Therefore, you can drag it with the mouse or finger as you need along the streets you need and it will show you both the distance and the shortest path draggable: true,

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question