Code Monkey home page Code Monkey logo

regions's Introduction

regions (code name osme)

The source of World's administrative divisions.

This is a module designed for:

  • Yandex,
  • Google,
  • Leaflet,
  • any other JS Maps to outline countries, counties and regions of the world.
  • being just a getJSON provider

Each time you want to display borders - use the regions, Luke.

NPM

Runs on top of information from OpenStreetMap, Wikipedia, GeoNames, eSosedi and some other sources.

Created for and used by esosedi.org project - one of largest cartographical site in the World.

  • This is neither lib nor API. This is a service.
 import osme from 'osme';

or

 <script src="https://unpkg.com/osme"></script>
 // use window.osme

World

API

There is only 2 primary commands:

  • osme.geoJSON(addr, [options], [callback]):Promise - to get geoJSON for a region query
  • osme.geocode(point, [options], [callback], [errorCallback]):Promise - to find region by coordinates

Plus we include build-in wrappers for Yandex Maps API, Google Maps API and Leaflet.

  • osme.toGoogle(geoJson)
  • osme.toYandex(geoJson)
  • osme.toLeaflet(geoJson)

All collections will have interface of .add .remove .setStyles .addEvent .removeEvent.

Result it very simple - you can display any continent, country or state on a map.

As Service

The module consists in two parts, and this part is a client side. It does not contain any data, always striming it from the server side at data.esosedi.org. Server-side also implements online navigator via database to help you find proper place.

  • base service runs as 'http' service. Not https!, to https is provided by cloudflare and geolocated.org.

What I can load?

So, you can load:

  • world - all countries of the World.
  • geoScheme - 21 macro region of the World. Africa, Americas, Asia, Europe, Oceania, Eastern Africa, Middle Africa, Northern Africa, Southern Africa, Western Africa, Cariebbean, Central America, Northern America, South America, Central Asia, Eastern Asia, South-Eastern Asia, Southern Asia, Western Asia, Eastern Europe, Northern Europe, Southern Europe, Western Europe, Australia and New Zealand, Melanesia, Micronesia, Polynesia.
  • iso3166-1 code. Country code. US, AU, DE and so on
  • iso3166-2 code. Region. US-WA, AU-NSW, RU-MOW and so on
  • special exports. bigMoscow, Moscow, SaintPetersburg, bigPiter and so on. Open a Pull Request if you need a special one.
  • number - as a OpenStreetMap RelationID. Ie - you can get contour of USA using US or 148838, there is no difference.

Example

  • And check /examples folder!
import osmeRegions from 'osme';
osme.geoJSON('FR').then( geojson => osme.toGoogle(geojson).add(map));

A bit bigger one:

// ask for some region
osme.geoJSON('US'/*addr*/, {lang: 'de'}, function (data) {
    // data is pure GEOJSON
    
    // you can create some helpers
    var yandexGeoObjectColletionWrapper = osme.toYandex(data);
    // or
    var googleDataWrapper = osme.toGoogle(data);
    // or 
    var leafletDataWrapper = osme.toLeaflet(data);

    // call .add to add data into the map
    yandexGeoObjectColletionWrapper.add(map);
    // call .remove to remove
    googleDataWrapper.remove();
    
    // call setStyles to setup styles
    leafletDataWrapper.setStyles(jsonFeatureIn => {
       return styleOptions
    });
    
    // And you also can control events.
    *.addEvent(event,function(feature, apiType, apiObject, apiEvent){});
    *.removeEvent();
})

// PS: OR you can use geoJSON as geoJSON. With out helpers
    new L.geoJson(data).addTo(map);

.geoJSON

  • osme.geoJSON(addr, options, callback) Where: addr is OSM RelationId, ISO3166-2 code(US/DE/GB or RU-MOS/US-TX etc, or world's region name options is a object of { lang, quality, type, nocache, postFilter, recombine, scheme }. All are optional.

      - lang - prefered language (en,de,ru)
      - quality – set 0 to get geomentry for fullHD resolution. -1,0,+1,+2 for /4, x1, x4, x16 quality.
      - type - null|'coast'. 
        - null to get `raw` `maritime` administrative borders, including terrotorial water.
        - "coast", to cut off coast lines.
      - nocache - turns of internal client-side cache
      - postFilter, recombine, scheme - to be used only by advanced users. 
    

If you dont know relationId(addr) for region you need, you can:

  1. Traverse map database at http://data.esosedi.org.
  2. Use reverse geocode, via this lib, or via REST call - http://data.esosedi.org/geocode/v1?[lng=(ru|en)]&point=x,y[&seq=?][&callback=?]
  3. Use iso3166 library to get administrative divisions as a list.

type=coast

Type coast will return information you want - pretty borders. Very hi-detailed borders. Here is comparison between borders for Greece with and without maritime. Greece Difference - 154kb versus 251.

PS:

Information available for ~300k regions in 3 languages(en, de, ru) and some secret modes.

This module uses CORS to transport JSON via different hosts.

You can store geojson produced by this module, or cache packed json files from orinal data endpoint.

Just change data-endpoint by executing osme.setHost command.

  • Remember: We have to provide copyright information, and you have to display it.

Data format is quite simple and compact. It is look like topojson, but more "binary" and contains data like schemes etc. After all you will get standard geoJSON. You can use it by your own risk.

More Examples:


// request Moscow
osme.geoJSON('RU-MOW', {lang: 'ru'}, function (data) {
    var collection = osme.toYandex(data, ymaps);
    collection.add(geoMap);

    geoMap.setBounds(collection.collection.getBounds(), {duration: 300});
    
    var strokeColors = [
        '#000',
        '#F0F',
        '#00F',
        '#0FF',
    ];
    var meta = data.metaData,
        maxLevel = meta.levels[1] + 1;
        
    // colorize the collection    
    collection.setStyles(function (object, yobject) {
        var level = object.properties.level;
        return ({
            zIndex: level,
            zIndexHover: level,
            strokeWidth: Math.max(1, level == 2 ? 2 : (maxLevel - level)),
            strokeColor: strokeColors[maxLevel - level] || '#000',
            fillColor: '#FFE2',
        });
    });

Moscow

setStyles

You can do anything like country coloring (http://jsfiddle.net/9o9ak7fb/18/), or making "old" Moscow (http://jsfiddle.net/9o9ak7fb/17/). OSMe provide geo data, you provide logic.

var countryColors={
    'CA': "F00",
    'IN': "0F0",
    'US': "00F",
    'RU': "F0F"
};

function setColors(collection, countryColors){
     // You know this function
     collection.setStyles(function (object) {
        // get ISO counry code and color it
        var iso = (object.properties.properties.iso3166 ||'').toUpperCase(),
            color=countryColors[iso];
        return ({
            strokeWidth: 1,
            strokeColor: color?'#000':"666",
            fillColor: color || 'EEE',
            visible: !!color
        });
    });
}

//...
osme.geoJSON('world',{}).then(data => {
  const collection = osme.toGoogle(data);
  setColors(collection, countryColors);
  collection.add(map);
});

Colour

addEvents

  //any event - click, dblclick and so on.
 const event = collection.addEvent('dblclick', function (object, type, target, event) {
     // object - object itself
     // type – [eventName, provider('yandex','google')]
     // target – Maps API`s feature (polygon) 
     // event – original event    
    event.preventDefault();
 });
 collection.removeEvent(event);

And what about boundary dispute? Crimea, Kosovo, etc..

Magic of Recombine

Recall strange parameter in options, field named recombine. This is not about boundaries, this is about recombination. It is almost as language - en-US, or en-GB..

  • It can be string, and will be treated as key in scheme. Default equals to language.
  • Object with key - relation id, and value - javascript code.

See disputed-borders.html in /examples.

Recombination allow you to create new geometry by combination of others.

For example something from internal cuisine - this code included in world.json file, and executed automatically

{
    disputedBorders: {
        ru: {
            60199/*UA*/: 'return region.hasParent(60199) && region.osmId != 72639 && region.osmId != 1574364 && region.osmId!=421866;',
            60189/*RU*/: 'return !region.hasParent(60189) && (region.osmId == 60189 || region.osmId == 72639 || region.osmId == 1574364)',
        }
    },
    postFilter: 'return !region.hasParent(60199);', //remove UA*
}

What this function do - it generates Ukraine without Crimea, or Russia with.

  • for #60199(Ukraine) - select all objects in 60199, but not Crimea and Kiev(internal shape)
  • for #60189(Russia) - selects RU, plus Crimea regions.
  • later - remove all regions of UA (exists in geoJSON file for this recombination) cos we require countries.

You can set options.recombine to a string ('ru' in this example) to select desired scheme, or set new scheme object.

  • By default recombine===lang.

By the same way you can join SJ to NO or GF to FR (one will understand).

You can create Merica by joining US to CA and MX or create EuroUnion.

The difference between recombination and just displaying everything you need - the result of recombination is borderless. You will get not a pack of shapes, but BIG one.

Recombination can be used to join any set of regions in one. This is usefull in many cases.

 osme.geoJSON('349035', {lang: 'en'}, function (data, pureData) {
    var coords=osme.recombine(pureData, { // yes, you can use pure data
        filter: function (region) {
            // somethere in Province of Barcelona (349035) and Barcelona(2417889) or adjacent
            // remember - you have to discard #349035 or you got duplicate.
            return region.hasParent(349035) && (region.hasBorderWith(2417889) || region.osmId == 2417889);
        }
    });
    for(var j in coords.coordinates) {
        var region = new ymaps.GeoObject({
            geometry: {
                type: 'Polygon',
                fillRule: 'nonZero',
                coordinates: osme.flipCoordinate([coords.coordinates[j]])
            }
        }, {
            opacity: 0.8,
            fillColor: 'FEE',
            strokeColor: 'F00',
            strokeWidth: 2,
            pixelRendering: 'static',
            draggable: true
        });
        geoMap.geoObjects.add(region);
    }
}

And you got mini Barcelona Barcelona

Where is also exists options.scheme - yet another recombination function. It also sometimes exists in source geoJSON file. The goal still simple - some regions lays on the top of other, and do not have adjacent borders - Kiev, for example, and Kiev province. Scheme just adds "hole" to province.

You dont need to understand all of this - just use.

Remember

  • ! As any UGC project, may contain, contain and will contain errors, holes in data and mistakes.

Cheers, Kashey.

regions's People

Contributors

rifler avatar thekashey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

regions's Issues

Город Ульяновск

Доброго времени суток. Не подскажете, что стоит передать, чтобы получить именно г. Ульяновск, с делением на районы? На данный момент получилось отобразить только в масштабах области, что слишком крупно. При передаче ID с OPM нет деления на районы. Благодарю за внимание

https://www.openstreetmap.org/search?query=%D0%A3%D0%BB%D1%8C%D1%8F%D0%BD%D0%BE%D0%B2%D1%81%D0%BA#map=12/54.3057/48.4098

Библиотеку нельзя использовать под https

Библиотеку нельзя использовать на сайте с "https".
Пожалуйста, сделайте такую возможность!

Под капотом библиотеки выполняется запрос:
http://data.esosedi.org/geocode/v1?point=57.153033,65.534328&lng=ru
А вот такое не пашет:
https://data.esosedi.org/geocode/v1?point=57.153033,65.534328&lng=ru
Отсюда получаем проблемы... И классическую ошибку браузера:

Mixed Content: бла-бла-бла was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://data.esosedi.org/geocode/v1?point=57.153033,65.534328&lng=ru'. This request has been blocked; the content must be served over HTTPS.

Западный административный округ и кусочек "москва"

При запросе RU-MOW получаю кусочек "москва" без АО, который должен быть в западном АО. Соответственно, при запросе osmId 226149 кусочка округа не хватает, рекомбинация мне не поможет, osmId кусочка совпадает с osmId всей москвы

Более мелкое деление "городского округа Барнаул"

Прошу прощения, если не туда пишу.

Вижу, что ваша библиотека может отдать мне городской округ Барнаул:
https://www.openstreetmap.org/relation/1440772

Задача: получить не городской округ Барнаул, а более мелкое деление -- сам город Барнаул, он на самом деле МЕНЬШЕ, т. к. на сайте кадастра есть город Барнаул:
https://egrp365.ru/map/?id=g44v61

Вопрос: где вообще взять это самое более мелкое деление?
Пока что прихожу к выводу, что НИГДЕ.
Подскажите пожалуйста...

How I can pick an OpenStreetMap 'way'

like this – Линия: Нудоль (229341599). I try to filter it in 'RU-MOS' (Moscow Region),

osmeRegions.geoJSON('RU-MOS', {lang: 'ru', quality: 3}, function (data, pureData) {
            var coords = osmeRegions.recombine(pureData, {
                filter: function(region) {
                    return region.osmId==229341599;
                }
            });
            ...

but it didn't work. May be because it is not OpenStreetMap _'boundary'. It is OpenStreetMap **'way'. How I can add this **'way'_ to my map?

Новомосковский округ и Аэропорт Внуково

Нет ли возможности удалить из полигона Новомосковского АО (osmId=2263058) аэропорт Внуково - самый южный полигон Западного АО (osmId=226149)?

В настоящий момент полигон аэропорта присутствует в Западном АО, но не вырезан из Новомосковского АО. В результате происходит наложение полигонов.

screenshot 79
screenshot 80

osme.geoJSON is not a function

I try to execute an example, but it gives an error

osme=require('osme'); osme.geoJSON('FR').then( geojson => osme.toGoogle(geojson).add(map));
                                    ^
TypeError: osme.geoJSON is not a function

Не могу удалить залитую область

Выполняю заливку района цветом, что бы подсветить этот район.

Не могу убрать заливку с области, что бы выделить другую, они накапливаются

image

mapping data by sub-region, varying degree of darkness

This is a neat project.

I'd like to use your project as the basis of a data mapping task I'm working on. At the moment I have the following data:

RO-B, 9
PL-MZ, 24
SE-C, 3
DE-NI, 5
PL-DS, 14
ES-CM, 11
RO-IS, 2
DE-BY, 51
SE-Z, 18
CH-BE, 10
PL-WP, 1
ES-IB, 1
DE-BW, 21
DE-BE, 24
DE-BB, 1
IE-M, 26
ES-PV, 1
DE-SN, 6
CH-ZH, 31
ES-GA, 1
NL-GE, 2
IE-U, 1
ES-AN, 4
FR-J, 82
DE-HH, 34
PL-PD, 1
PL-LD, 6
GB-WLS, 60
GB-ENG, 8619
RO-BV, 45
CH-VD, 2
PL-SL, 1
DE-HE, 17
SE-I, 1
HU-PE, 4
PL-MA, 4
SE-AB, 3
CH-BS, 20
ES-CT, 31
DE-TH, 25
IE-C, 1
CZ-ST, 1
DE-NW, 29
NL-NH, 3
DE-RP, 9
CZ-PR, 4
IE-L, 134
HU-BU, 10
RO-CJ, 1
GB-NIR, 29
ES-MD, 33
CH-LU, 11
GB-SCT, 172
CH-GE, 3
BE-BRU, 30
BE-VLG, 25

These are ISO3166-2 regional codes, and a corresponding number of data points located in that region.

What I would like to do is color in the map according to this data, so that the more points are located there the darker it would appear.

Would it be possible for me to modify the example.html to achieve that?

Is there some way that I could limit the view of the map to only Europe?

Что это и как использовать?

Привет!

Сорри, я так и не воткнул что это и как это использовать.
Поскольку я не знаю как правильно задать вопрос, зайду с конкретики.
Нужно изготовить картинки по типу такой:

Кетай

но не только для стран, но по регионам России например, или штатам штатов.
Могу ли я это взять и использовать для данной задачи?

неверное название района

Россия -> Алтайский Край -> Шелаболихинский район, их два, рядом. За место одного из них должен быть Тальменский район.

CORS?

Привет. А этот метод можно использовать на сайте? У меня, вот, ругается...
XMLHttpRequest cannot load http://data.esosedi.org/regions/v1/?lang=ru_60189&type=coast. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:1000' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.
На Node.js работает, в jsFiddle работает, в браузере, вот не хочет.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.