Html open street maps

Работа с картой OpenStreetMap

Сегодня OpenStreetMap набирает огромную популярность среди веб-картографических проектов. Причинами этого является его некоммерческий стиль, подробная свободная и бесплатная географическая карта мира, а также то, что сервис Google Maps, который до этого времени использовало значительное количество сайтов, стал платным! Также следует заметить, что OpenStreetMap появился задолго до Google Maps.

На сайте Openstreetmap.org размещена карта, онлайн-инструменты по ее редактированию, дневники участников, форум, справочная вики и раздел помощи. В Openstreetmap, как и в Wikipedia, основную часть данных добавляют частные лица, заинтересованные в развитии проекта. По каждому участку карты видна история правок, что в свою очередь снижает возможность вандализма и, в некоторых случаях, позволяет оптимизировать работу нескольких человек, занятых одним и тем же участком карты.

Данная статья будет дополняться по ходу реализации функционала различных проектов, связанных с OpenStreetMap.

Для полноценной работы карты OpenStreetMap мы будем использовать библиотеку JavaScript Leaflet, которая небольшая, простая и имеет отличную документацию.

В этой статье рассмотрим пример, который показывает, как:

– настроить простую карту с помощью библиотеки Leaflet;

– загрузить местоположение маркера;

– отображать координаты при нажатии на карте, или создавать визуально маркеры.

Нам обязательно потребуется загрузить библиотеки jQuery и Leaflet:

Данные строки включают библиотеки CSS и JavaScript, которые нам нужны для отображения и работы карты. В этом примере мы ссылаемся на эти файлы, хранящиеся на удаленном сервере с использованием CDNJS. Другой вариант – разместить эти файлы самостоятельно, но преимущества использования CDNJS:

1. Облегчает нагрузку на ваш сервер.

2. CDN распространяют контент, чтобы он был ближе к пользователю, что ускоряет загрузку.

3. Браузеры ограничивают количество запросов HTTP для каждого хоста, поэтому доступ к нескольким различным хостам позволяет извлекать данные параллельно, что приводит к более быстрому отображению страницы.

4. Если пользователь посетил другой сайт с использованием того же сценария, он автоматически будет сохранен в кэше, что позволит на вашем сайте не загружать его снова и значительно ускорит отображение страницы.

После загрузки скриптов и стилей необходимо включить в файл идентификатор карты:

Мы создаем Div под названием map с высотой и шириной, который будет заполнен нашей картой, когда мы создадим ее в нашем JavaScript. Если мы не укажем ширину, карта будет динамически регулировать ширину для страницы.

Последняя часть этого файла является ключом. Здесь мы загружаем JavaScript, который выполняет настройку и отображение нашей карты.

  
var map = L.map('map').setView([-16.50629, -68.12703], 12);

создаст новую карту, назначит ее идентификатор – map и установит некоторые параметры. В этом случае мы центрируем начальный вид, заданным координатами широты и долготы. Также мы устанавливаем уровень масштабирования 12. Здесь есть много других опций, которые вы можете настроить.

L.tileLayer('https://.tile.openstreetmap.org///.png', < attribution: '© OpenStreetMap contributors', subdomains: ['a','b','c'] >).addTo(map);

Этот код добавляет слой на карту, сообщая ей, какой набор слоев отображать и где их получить. Есть несколько разных серверов, которые вы можете использовать – или вы можете разместить свой собственный.

Читайте также:  Import java util exception

Опять же, у Leaflet есть много опций, которые можно использовать при создании tileLayer. В нашем примере первым аргументом является шаблон URL, поэтому Leaflet знает, как правильно получать слои с серверов. Далее идет атрибуция – это то, что отображается в правом нижнем углу карты. Важно, чтобы вы добавили правильную информацию для правильной атрибуции набора слоев.

Наконец, у нас есть список поддоменов. Этот массив строк подставляется в часть шаблона URL. Обратите внимание, что этот список зависит от серверов слоев, которые вы используете. Эта опция позволяет браузеру загружать файлы с нескольких серверов одновременно, что приводит к более быстрой загрузке страницы и более быстрым обновлениям, когда пользователь перетаскивает карту.

Хорошо, теперь у нас есть интерактивная карта, которую мы можем перетаскивать, увеличивать и уменьшать. Следующее, что необходимо сделать, это добавить маркеры.

L.marker([-16.50629, -68.12703]).addTo(map).bindPopup("My Marker");

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

Маркеры Leaflet предлагают много вариантов для настройки. В нашем примере мы создаем маркер в определенном месте, привязываем к нему простое всплывающее окно и добавляем его на нашу карту. В данной строке указывается широта и долгота, а также данные, отображаемые во всплывающем окне.

Основная задача карты выполнена, мы показали маркеры и выведи необходимую информацию. Но как добавлять координаты для маркера? Вот рабочий пример:

  

Теперь, при нажатии на карте, будет выводится ширина и долгота. Немного доработав скрипт, можно отправлять данные с помощью библиотеки jQuery.

Источник

OpenLayers Simple Example

This simple example may help if you are Deploying your own Slippy Map. This DHTML snippit will bring in the OpenLayers javascript library and use it to show an OSM map!

Note: OpenStreetMap is serving the tile images

Please note that tile images are coming from the OpenStreetMap servers. Although OSM are supporting this kind of usage at the moment, we offer no guarantees. There may be downtime (planned or unplanned), and tile URLs may change.

If you are expecting heavy user load, then you should discuss with everyone first (Contact). You should consider following the other instructions on creating your own tiles, or set up your own squid cache for tiles. This will reduce the dependency for you, and will ease bandwidth usage for the OSM servers.

Of course the images themselves (our maps) change over time too, not necessarily for the better.

Instructions

First, create a folder to work in. Download a stable release of OpenLayers from openlayers.org (note: this is a link to the older version 2 which those examples are based on), and uncompress it. Copy the `OpenLayers.js` file and the `theme` directory to the base of the folder. Then, copy one of the following into a new HTML file, and view it in a browser.

Читайте также:  Clone object list in java

The smallest example

DOCTYPE HTML> title>OpenLayers Simplest Example/title> div id="demoMap" style="height:250px">/div> script src="OpenLayers.js">/script> script> map = new OpenLayers.Map("demoMap"); map.addLayer(new OpenLayers.Layer.OSM()); map.zoomToMaxExtent(); /script> 
  • initialise a Map object with a DIVs id
  • add a OpenStreetMap Layer
  • force the tiles to show by calling zoomToMaxExtent, you could also call zoomToExtent, but for that you need a bounds object in the correct projection.

A little more extensive example

DOCTYPE HTML> html> head> title>OpenLayers Demo/title> style type="text/css"> html, body, #basicMap  width: 100%; height: 100%; margin: 0; > /style> script src="OpenLayers.js">/script> script> function init()  map = new OpenLayers.Map("basicMap"); var mapnik = new OpenLayers.Layer.OSM(); var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984 var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection var position = new OpenLayers.LonLat(13.41,52.52).transform( fromProjection, toProjection); var zoom = 15; map.addLayer(mapnik); map.setCenter(position, zoom ); > /script> /head> body onload="init();"> div id="basicMap">/div> /body> /html> 

Extensions

Other tile sets

If you are deploying your own tile images (for example, with Mapnik), just use the layer definition below:

var newLayer = new OpenLayers.Layer.OSM("New Layer", "URL_TO_TILES/$/$/$.png", numZoomLevels: 19>); map.addLayer(newLayer); 

The addition of /$/$/$.png URL template has been required since the 27th June 2009.

Change the url and numZoomLevels as appropriate.

Restricting the bounds & zoom levels

This restricts the map to showing the area around Oxford, and zoom levels 13-16. To add lower zooms, add new numbers in the resolutions array (each one is double the next).

var fromProjection = new OpenLayers.Projection("EPSG:4326"); // transform from WGS 1984 var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection var extent = new OpenLayers.Bounds(-1.32,51.71,-1.18,51.80).transform(fromProjection,toProjection); function init()  var options =  restrictedExtent : extent, controls: [ new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoomBar(), new OpenLayers.Control.Attribution() ] >; map = new OpenLayers.Map("Map", options); var newLayer = new OpenLayers.Layer.OSM( "New Layer", "URL_TO_TILES/$/$/$.png", zoomOffset: 13, resolutions: [19.1092570678711,9.55462853393555,4.77731426696777,2.38865713348389]> ); map.addLayer(newLayer); map.setCenter(new OpenLayers.LonLat(-1.25,51.75).transform(fromProjection,toProjection), 0); // 0=relative zoom level > 

Altering the location of the attribution text and scale line

You can override the location of the attribution text and scale line, and the font used, by adding the following lines in the style section

div.olControlAttribution, div.olControlScaleLine  font-family: Verdana; font-size: 0.7em; bottom: 3px; > 

Add Markers

DOCTYPE HTML> html> head> title>OpenLayers Simplest Example/title> /head> body> div id="Map" style="height:250px">/div> script src="OpenLayers.js">/script> script> var lat = 47.35387; var lon = 8.43609; var zoom = 18; var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984 var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection var position = new OpenLayers.LonLat(lon, lat).transform( fromProjection, toProjection); map = new OpenLayers.Map("Map"); var mapnik = new OpenLayers.Layer.OSM(); map.addLayer(mapnik); var markers = new OpenLayers.Layer.Markers( "Markers" ); map.addLayer(markers); markers.addMarker(new OpenLayers.Marker(position)); map.setCenter(position, zoom); /script> /body> /html> 

Use Proj4js for other transformations

The example lets you use WGS84 coordinates to navigate in a sphericalMercator projected OSM map. If your coordinates are in a different projection, you can add Proj4js to perform reprojections.

Add the proj4js.js script from http://svn.osgeo.org/metacrs/proj4js/trunk/lib/proj4js-combined.js to your page (after the OpenLayers lib!)

Add your projection defintion (these are obtainable from the Proj4 project, you need the a record from \proj\nad\epsg

Example for EPSG:28992 (new RD)

Proj4js.defs[«EPSG:28992»] = «+title=Amersfoort / RD New +proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m +no_defs»;

Then, you can use EPSG:28992 coordinates and this epsg code in the transformfunction instead of WGS84

map.setCenter( new OpenLayers.LonLat(155000,465000) // Center of the map .transform( new OpenLayers.Projection("EPSG:28992"), // transform from new RD new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection ), 15); // Zoom level 

Develop this example?

Feel free to edit this page with improvements.

This example was originally created by Harry Wood (and anyone else who edits this page). It is intentionally more basic, with only one layer defined, and no support for URL params (permalink) etc. So adding these features is not necessarily an improvement. In fact, if you have ideas for making this even more simple, that would be good.

  • OpenLayers Marker Add a simple static marker
  • Openlayers POI layer example — Explains how to show POI markers with an overlay layer
  • Full documentation of classes used is at the OpenLayers site or in the more up to date developer docu
  • For further help and inspiration on using OpenLayers, you may wish to see the OpenLayers Examples.
  • Another example of embedding a slippy OSM map with a GPX track on your website, based on the text above.
  • Embed an OSM map with your track in webpage in the way similar to Google Maps (just provide a GPX or KML file).

Источник

Оцените статью