Примеры работы с разными map API

16 июня 2015

bd72073cЕсть много статей на тему знакомства с Google Map Api и Yandex Map Api, но про остальные картографические сервисы не так много практического материала. В недавнем времени работал с Api:

  1. Google map
  2. Yandex map
  3. Yahoo map
  4. Bing map
  5. OpenStreet map

И хотел обобщить работу с вышеупомянутыми сервисами, а именно инициализация карты и установление маркеров по клику мышки. Материалы в статье представлены в виде Html кода, javascript и результата — скриншота, а так же исходники на vs 2010 MVC3.

С Google map ситуация проще всего: практического материала много, мой пример выглядит следующим образом:
Html page:

<code><span class="tag"><<span class="title">script</span> <span class="attribute">type</span>=<span class="value">"text/javascript"</span> <span class="attribute">src</span>=<span class="value">"http://maps.google.com/maps/api/js?sensor=false"</span> ></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">script</span> <span class="attribute">src</span>=<span class="value">"@Url.Content("</span>~/<span class="attribute">Scripts</span>/<span class="attribute">jquery-1.5.1.min.js</span>")" <span class="attribute">type</span>=<span class="value">"text/javascript"</span>></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">script</span> <span class="attribute">src</span>=<span class="value">"@Url.Content("</span>~/<span class="attribute">Scripts</span>/<span class="attribute">LoadGoogle.js</span>")" <span class="attribute">type</span>=<span class="value">"text/javascript"</span>></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">h2</span>></span>GoogleMap<span class="tag"></<span class="title">h2</span>></span> <span class="tag"><<span class="title">div</span> <span class="attribute">id</span>=<span class="value">"map"</span> <span class="attribute">style</span>=<span class="value">"width: 1400px; height: 500px;"</span>></span><span class="tag"></<span class="title">div</span>></span> </code>

Script:

<code>$(document).ready(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span> initialize(); }); <span class="comment">//инициализация карты в div "map"</span> <span class="function"><span class="keyword">function</span> <span class="title">initialize</span><span class="params">()</span> {</span> <span class="keyword">var</span> haightAshbury = <span class="keyword">new</span> google.maps.LatLng(<span class="number">51.0532</span>, <span class="number">31.83</span>);<span class="comment">//(долгота, широта)</span> <span class="keyword">var</span> mapOptions = { zoom: <span class="number">12</span>,<span class="comment">//масштаб</span> center: haightAshbury,<span class="comment">//позиционируем карту на заданые координаты</span> mapTypeId: google.maps.MapTypeId.TERRAIN<span class="comment">//задаем тип карты</span> }; map = <span class="keyword">new</span> google.maps.Map(document.getElementById(<span class="string">"map"</span>), mapOptions);<span class="comment">//инициализация карты</span> google.maps.event.addListener(map, <span class="string">'click'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(event)</span> {</span> addMarker(event.latLng); });<span class="comment">//добавляем событие нажание мышки</span> } <span class="comment">//функция добавления маркера</span> <span class="function"><span class="keyword">function</span> <span class="title">addMarker</span><span class="params">(location)</span> {</span> <span class="keyword">var</span> shadow = <span class="keyword">new</span> google.maps.MarkerImage(<span class="string">'/Images/roles.png'</span>, <span class="keyword">new</span> google.maps.Size(<span class="number">37</span>, <span class="number">32</span>), <span class="keyword">new</span> google.maps.Point(<span class="number">0</span>, <span class="number">0</span>), <span class="keyword">new</span> google.maps.Point(<span class="number">0</span>, <span class="number">32</span>)); <span class="comment">// Теневое изображение</span> <span class="keyword">var</span> image = <span class="keyword">new</span> google.maps.MarkerImage(<span class="string">'/Images/smilies.png'</span>, <span class="keyword">new</span> google.maps.Size(<span class="number">20</span>, <span class="number">32</span>), <span class="keyword">new</span> google.maps.Point(<span class="number">0</span>, <span class="number">0</span>), <span class="keyword">new</span> google.maps.Point(<span class="number">0</span>, <span class="number">32</span>)); <span class="comment">//изображение маркера</span> marker = <span class="keyword">new</span> google.maps.Marker({ position: location, map: map, shadow: shadow, icon: image, title: <span class="string">"My title!)"</span>, zIndex: <span class="number">999</span> });<span class="comment">//добавление маркера</span> </code>

В результате получим карту Google c возможностью добавлять маркеры:

53ce9ecbДля инициализации Yandex map вам понадобится ключ доступа к сервису и следующий пример:
Html page:

<code><span class="tag"><<span class="title">script</span> <span class="attribute">src</span>=<span class="value">"http://api-maps.yandex.ru/1.1/index.xml?key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"</span> <span class="attribute">type</span>=<span class="value">"text/javascript"</span>></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">script</span> <span class="attribute">src</span>=<span class="value">"@Url.Content("</span>~/<span class="attribute">Scripts</span>/<span class="attribute">jquery-1.5.1.min.js</span>")" <span class="attribute">type</span>=<span class="value">"text/javascript"</span>></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">script</span> <span class="attribute">src</span>=<span class="value">"@Url.Content("</span>~/<span class="attribute">Scripts</span>/<span class="attribute">LoadYandex.js</span>")" <span class="attribute">type</span>=<span class="value">"text/javascript"</span>></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">h2</span>></span>YandexMap<span class="tag"></<span class="title">h2</span>></span> <span class="tag"><<span class="title">div</span> <span class="attribute">id</span>=<span class="value">"YMapsID"</span> <span class="attribute">class</span>=<span class="value">"YMaps YMaps-cursor-grab"</span> <span class="attribute">style</span>=<span class="value">"width: 1400px; height: 500px;"</span>></span> <span class="tag"></<span class="title">div</span>></span> </code>

Script:

<code>$(document).ready(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span> initialize(); }); <span class="function"><span class="keyword">function</span> <span class="title">initialize</span><span class="params">()</span> {</span> map = <span class="keyword">new</span> YMaps.Map(document.getElementById(<span class="string">"YMapsID"</span>));<span class="comment">//инициализация карты</span> map.setCenter(<span class="keyword">new</span> YMaps.GeoPoint(<span class="number">31.87</span>, <span class="number">51.0532</span>)<span class="comment">//(широта, долгота)</span> , <span class="number">12</span> <span class="comment">//Масштаб</span> , YMaps.MapType.MAP);<span class="comment">//тип карты</span> map.addControl(<span class="keyword">new</span> YMaps.TypeControl());<span class="comment">//смена типа карты</span> map.addControl(<span class="keyword">new</span> YMaps.ToolBar());<span class="comment">//инструменты</span> map.addControl(<span class="keyword">new</span> YMaps.Zoom());<span class="comment">//смена масштаба</span> map.addControl(<span class="keyword">new</span> YMaps.MiniMap());<span class="comment">//Небольшая отображающая местоположение</span> map.addControl(<span class="keyword">new</span> YMaps.ScaleLine());<span class="comment">//Отображение масштаба</span> YMaps.Events.observe(map, map.Events.Click, <span class="function"><span class="keyword">function</span> <span class="params">(map, mEvent)</span> {</span> addMarker(mEvent.getGeoPoint()); });<span class="comment">// событие щелчка мыши на карте</span> } <span class="comment">//функция добавления маркера </span> <span class="function"><span class="keyword">function</span> <span class="title">addMarker</span><span class="params">(location)</span> {</span> <span class="keyword">var</span> geoPlacemark = <span class="keyword">new</span> YMaps.Placemark(<span class="keyword">new</span> YMaps.GeoPoint(location.__lng, location.__lat), { draggable: <span class="number">1</span> }); <span class="comment">//координаты добавления метки</span> geoPlacemark.name = <span class="string">"Название чего то"</span>; geoPlacemark.description = <span class="string">"описание чего то"</span>; map.addOverlay(geoPlacemark);<span class="comment">//добавление метки </span> } </code>

В результате получим карту Yandex c возможностью добавлять маркеры:

Яндекс картаОбратите внимание на координаты, в Google идет сначала долгота, потом широта, а в Yandex наоборот!

Пример работы с Yahoo map api:
Html page:

<code><span class="tag"><<span class="title">script</span> <span class="attribute">type</span>=<span class="value">"text/javascript"</span> <span class="attribute">src</span>=<span class="value">"http://api.maps.yahoo.com/ajaxymap?v=3.8&appid=appidhere"</span>></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">script</span> <span class="attribute">src</span>=<span class="value">"@Url.Content("</span>~/<span class="attribute">Scripts</span>/<span class="attribute">LoadYahoo.js</span>")" <span class="attribute">type</span>=<span class="value">"text/javascript"</span>></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">body</span> <span class="attribute">onload</span>=<span class="value">"initialize_ymap()"</span>></span> <span class="tag"><<span class="title">h2</span>></span>YahooMap<span class="tag"></<span class="title">h2</span>></span> <span class="tag"><<span class="title">div</span> <span class="attribute">id</span>=<span class="value">"ymap"</span> <span class="attribute">style</span>=<span class="value">"width: 1400px;height: 500px;"</span>></span><span class="tag"></<span class="title">div</span>></span> <span class="tag"></<span class="title">body</span>></span> </code>

Script:

<code><span class="function"><span class="keyword">function</span> <span class="title">initialize_ymap</span><span class="params">()</span> {</span> <span class="keyword">var</span> yPoint = <span class="keyword">new</span> YGeoPoint(<span class="number">51.0532</span>, <span class="number">31.83</span>);<span class="comment">//(долгота, широта)</span> <span class="keyword">var</span> map = <span class="keyword">new</span> YMap(document.getElementById(<span class="string">'ymap'</span>));<span class="comment">//инициализация карты</span> map.setMapType(YAHOO_MAP_SAT);<span class="comment">//тип карты</span> map.drawZoomAndCenter(yPoint, <span class="number">6</span>);<span class="comment">//масштаб</span> map.addTypeControl();<span class="comment">//добавление контроля типа</span> YEvent.Capture(map, EventsList.MouseClick, reportPosition); <span class="comment">//событие нажатия на карте</span> <span class="comment">//функция добавления маркера</span> <span class="function"><span class="keyword">function</span> <span class="title">reportPosition</span><span class="params">(_e, _c)</span>{</span> <span class="keyword">var</span> mapmapCoordCenter = map.convertLatLonXY(map.getCenterLatLon()); <span class="comment">//переобразование координат </span> <span class="keyword">var</span> currentGeoPoint = <span class="keyword">new</span> YGeoPoint( _c.Lat, _c.Lon ); <span class="comment">//Точка куда нужно поставить маркер</span> map.addMarker(currentGeoPoint); <span class="comment">//Добавление маркера</span> } } </code>

В результате получим карту Yahoo c возможностью добавлять маркеры:

Yahoo картаДля работы с Bing map api нужно взять ключ:
www.microsoft.com/maps/developers/web.aspx
Пример работы с Bing map api:
Html page:

<code><span class="tag"><<span class="title">script</span> <span class="attribute">charset</span>=<span class="value">"UTF-8"</span> <span class="attribute">type</span>=<span class="value">"text/javascript"</span> <span class="attribute">src</span>=<span class="value">"http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"</span>></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">script</span> <span class="attribute">charset</span>=<span class="value">"UTF-8"</span> <span class="attribute">type</span>=<span class="value">"text/javascript"</span> <span class="attribute">src</span>=<span class="value">"https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&s=1"</span>></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">script</span> <span class="attribute">src</span>=<span class="value">"@Url.Content("</span>~/<span class="attribute">Scripts</span>/<span class="attribute">LoadBing.js</span>")" <span class="attribute">type</span>=<span class="value">"text/javascript"</span>></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">body</span> <span class="attribute">onload</span>=<span class="value">"GetMap();"</span>></span> <span class="tag"><<span class="title">h2</span>></span>BingMap<span class="tag"></<span class="title">h2</span>></span> <span class="tag"><<span class="title">div</span> <span class="attribute">id</span>=<span class="value">'mapDiv'</span> <span class="attribute">style</span>=<span class="value">"position:absolute; width:1400px; height:500px;"</span>></span><span class="tag"></<span class="title">div</span>></span> <span class="tag"></<span class="title">body</span>></span> </code>

Script:

<code><span class="function"><span class="keyword">function</span> <span class="title">GetMap</span><span class="params">()</span> {</span> <span class="keyword">var</span> map = <span class="keyword">new</span> Microsoft.Maps.Map(document.getElementById(<span class="string">"mapDiv"</span>), { credentials: <span class="string">"ххххххххxxxxxxxxxxxxxxxxx"</span>,<span class="comment">//ключ</span> center: <span class="keyword">new</span> Microsoft.Maps.Location(<span class="number">51.0532</span>, <span class="number">31.83</span>),<span class="comment">//(долгота,широта)</span> mapTypeId: Microsoft.Maps.MapTypeId.road,<span class="comment">//(тип карты)</span> zoom: <span class="number">8</span><span class="comment">//масштаб</span> }); <span class="comment">//Событие на кликание мышки на карте</span> Microsoft.Maps.Events.addHandler(map, <span class="string">'click'</span>, displayLatLong); <span class="function"><span class="keyword">function</span> <span class="title">displayLatLong</span><span class="params">(e)</span> {</span> <span class="keyword">if</span> (e.targetType == <span class="string">"map"</span>) { <span class="keyword">var</span> point = <span class="keyword">new</span> Microsoft.Maps.Point(e.getX(), e.getY());<span class="comment">//координаты вставки маркера</span> <span class="keyword">var</span> loc = e.target.tryPixelToLocation(point);<span class="comment">//позиция маркера</span> <span class="keyword">var</span> pin = <span class="keyword">new</span> Microsoft.Maps.Pushpin(loc);<span class="comment">//маркер</span> map.entities.push(pin);<span class="comment">//вставляем маркер</span> } } } </code>

В результате получим карту Bing c возможностью добавлять маркеры:

Карты BindПример работы с OpenStreet map api:

Html page:

<code><span class="tag"><<span class="title">script</span> <span class="attribute">src</span>=<span class="value">"http://www.openlayers.org/api/OpenLayers.js"</span>></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">script</span> <span class="attribute">src</span>=<span class="value">"@Url.Content("</span>~/<span class="attribute">Scripts</span>/<span class="attribute">LoadOpenStreet.js</span>")" <span class="attribute">type</span>=<span class="value">"text/javascript"</span>></span><span class="tag"></<span class="title">script</span>></span> <span class="tag"><<span class="title">body</span> <span class="attribute">onload</span>=<span class="value">"GetMap();"</span>></span> <span class="tag"><<span class="title">h2</span>></span>OpenStreetMap<span class="tag"></<span class="title">h2</span>></span> <span class="tag"><<span class="title">div</span> <span class="attribute">id</span>=<span class="value">"OSMap"</span> <span class="attribute">style</span>=<span class="value">"position:absolute; width:1400px; height:500px;"</span>></span><span class="tag"></<span class="title">div</span>></span> <span class="tag"></<span class="title">body</span>></span> </code>

Script:

<code><span class="function"><span class="keyword">function</span> <span class="title">GetMap</span><span class="params">()</span> {</span> map = <span class="keyword">new</span> OpenLayers.Map(<span class="string">"OSMap"</span>);<span class="comment">//инициализация карты</span> <span class="keyword">var</span> mapnik = <span class="keyword">new</span> OpenLayers.Layer.OSM();<span class="comment">//создание слоя карты</span> map.addLayer(mapnik);<span class="comment">//добавление слоя</span> map.setCenter(<span class="keyword">new</span> OpenLayers.LonLat(<span class="number">31.83</span>, <span class="number">51.0532</span>) <span class="comment">//(широта, долгота)</span> .transform( <span class="keyword">new</span> OpenLayers.Projection(<span class="string">"EPSG:4326"</span>), <span class="comment">// переобразование в WGS 1984</span> <span class="keyword">new</span> OpenLayers.Projection(<span class="string">"EPSG:900913"</span>) <span class="comment">// переобразование проекции</span> ), <span class="number">10</span> <span class="comment">// масштаб</span> ); <span class="keyword">var</span> layerMarkers = <span class="keyword">new</span> OpenLayers.Layer.Markers(<span class="string">"Markers"</span>);<span class="comment">//создаем новый слой маркеров</span> map.addLayer(layerMarkers);<span class="comment">//добавляем этот слой к карте</span> map.events.register(<span class="string">'click'</span>, map, <span class="function"><span class="keyword">function</span> <span class="params">(e)</span> {</span> <span class="keyword">var</span> size = <span class="keyword">new</span> OpenLayers.Size(<span class="number">21</span>, <span class="number">25</span>);<span class="comment">//размер картинки для маркера</span> <span class="keyword">var</span> offset = <span class="keyword">new</span> OpenLayers.Pixel(-(size.w / <span class="number">2</span>), -size.h); <span class="comment">//смещение картинки для маркера</span> <span class="keyword">var</span> icon = <span class="keyword">new</span> OpenLayers.Icon(<span class="string">'/Images/smilies.png'</span>, size, offset);<span class="comment">//картинка для маркера</span> layerMarkers.addMarker(<span class="comment">//добавляем маркер к слою маркеров</span> <span class="keyword">new</span> OpenLayers.Marker(map.getLonLatFromViewPortPx(e.xy), <span class="comment">//координаты вставки маркера</span> icon));<span class="comment">//иконка маркера</span> }); <span class="comment">//добавление событие клика по карте</span> } </code>

В результате получим карту OpenStreet c возможностью добавлять маркеры:

OpenStreet картаВот такие интересные примеры работы с картами, думаю кому то будут полезны.

Исходники на VS2010 MVC3.

Источник: http://habrahabr.ru/post/131249/

Написать комментарий

Адрес и телефон
E-mail: rs@corp2.net Skype: rudjuk
г. Киев, ул. Белорусская 30, офис. К2Р (схема проезда)
Мы в сети
Меню
www.megastock.ru Здесь находится аттестат нашего WM идентификатора 000000000000
Проверить аттестат
Наверх