This post will be a small, but hopefully useful. Today I'll talk about how I implemented search location by its address, and how I determine the current location of the user. All this is done on the basis of OpenLayers 2.
I hope that the reader is already familiar with the basics of working in OpenLayers and map with layers already created. If not, write in the comments, I'll try anything elaborate.
In the first place geolocation. IMHO, thanks to OL this issue is not labor intensive.
First, create the desired object:
and add it to the map (OpenLayersMap - it actually created the map object after the constructor OpenLayers.Map (options)):
With that sorted out, but what's next. Then you need to activate it. Again, it's simple:
The last thing I added - an event handler when the location is found. Register for this event and set the function to handle the event:
Now prepare the layer to display our items:
It remains to write a function OpenLayersFunc.Events.GeolocateOnLocationUpdated. The principle of action is as follows. When the event is triggered «locationupdated», call our function, in which event is passed to this event. And in this function, we did whatever on him, as we want. The code I tried to comment, so just watch:
Function adds animation pulsate pulsation in the circle. The parameter we pass the object of our circle - circle. Looks quite impressive:
All of the code of the implementation under the spoiler:
We turn now to a very similar thing - geocoding. I used the api from Google and have no regrets. Here we go:
First, create a new layer to display marker popups:
Here, everything is much easier. One function and one from jQuery, to make everything beautiful. Create an object geocoding, asks Google, we get the result and parse for jquery-ui.autocomplete to source. But hang on select centering card to that address, and add a marker with a window address:
Full code need not even hang it from the top and so all :)
PS I tried to write it here, I do not know, it came out or not. But still waiting for constructive criticism, suggestions :)
I hope that the reader is already familiar with the basics of working in OpenLayers and map with layers already created. If not, write in the comments, I'll try anything elaborate.
In the first place geolocation. IMHO, thanks to OL this issue is not labor intensive.
First, create the desired object:
var control = new OpenLayers.Control.Geolocate( bind: false, watch: true, geolocationOptions: { enableHighAccuracy: true, maximumAge: 0, timeout: 15000 });
and add it to the map (OpenLayersMap - it actually created the map object after the constructor OpenLayers.Map (options)):
OpenLayersMap.addControl(control);
With that sorted out, but what's next. Then you need to activate it. Again, it's simple:
control.activate();
The last thing I added - an event handler when the location is found. Register for this event and set the function to handle the event:
control.events.on({ "locationupdated": function(e) { OpenLayersFunc.Events.GeolocateOnLocationUpdated(e); } })
Now prepare the layer to display our items:
var layer = new OpenLayers.Layer.Vector('Geolocate', { styleMap: new OpenLayers.StyleMap( new OpenLayers.Style({ fillColor: '#000', fillOpacity: 0.1, strokeWidth: 0}) ) }); OpenLayersMap.addLayer(layer);
It remains to write a function OpenLayersFunc.Events.GeolocateOnLocationUpdated. The principle of action is as follows. When the event is triggered «locationupdated», call our function, in which event is passed to this event. And in this function, we did whatever on him, as we want. The code I tried to comment, so just watch:
var vector = OpenLayersMap.getLayersByName('Geolocate')[0]; vector.removeAllFeatures(); //очистили слой геолокации (чтобы не было дубляжей) var polygon = OpenLayers.Geometry.Polygon.createRegularPolygon(new OpenLayers.Geometry.Point(e.point.x, e.point.y), e.position.coords.accuracy / 2, 40, 0); var circle = new OpenLayers.Feature.Vector(polygon); //создали геометрию круга вокруг точки нашего местоположения и создали объект слоя var point = new OpenLayers.Feature.Vector(e.point, {}, { graphicName: 'cross', strokeColor: '#f00', strokeWidth: 1, fillOpacity: 0, pointRadius: 8 }); //также создаем саму точку vector.addFeatures([point, circle]); //и добавляем круг с точкой на слой if (OpenLayersFunc.Events.GeolocateFirstRun) { //это просто глобальная переменная, чтобы определить запускаем ли мы в первый раз pulsate(circle); //а это уже красота, смотрим дальше OpenLayersFunc.Events.GeolocateFirstRun = false; }
Function adds animation pulsate pulsation in the circle. The parameter we pass the object of our circle - circle. Looks quite impressive:
var pulsate = function(feature) { var point = feature.geometry.getCentroid(); var bounds = feature.geometry.getBounds(); var radius = Math.abs((bounds.right - bounds.left) / 2); var count = 0; var grow = 'up'; var resize = function() { if (count > 16) { clearInterval(window.resizeInterval); } var interval = radius * 0.03; var ratio = interval / radius; switch (count) { case 4: case 12: grow = 'down'; break; case 8: grow = 'up'; break; } if (grow !== 'up') { ratio = -Math.abs(ratio); } feature.geometry.resize(1 + ratio, point); vector.drawFeature(feature); count++; }; window.resizeInterval = window.setInterval(resize, 50, point, radius); };
All of the code of the implementation under the spoiler:
Geolocation
We turn now to a very similar thing - geocoding. I used the api from Google and have no regrets. Here we go:
First, create a new layer to display marker popups:
var layer = new OpenLayers.Layer.Vector('Geocoder', { styleMap: new OpenLayers.StyleMap( new OpenLayers.Style({ externalGraphic: '../images/geocoder_marker.png', graphicWidth: 32, graphicHeight: 32, graphicYOffset: -32 ) });
Here, everything is much easier. One function and one from jQuery, to make everything beautiful. Create an object geocoding, asks Google, we get the result and parse for jquery-ui.autocomplete to source. But hang on select centering card to that address, and add a marker with a window address:
var geocoder = new google.maps.Geocoder(); //создаем объект геокодирования $('#top-search-field').autocomplete({ //подключаем плагин к нашему полю ввода source: function(request, response) { //заполняем автодополнение результатами возможных адресов geocoder.geocode({'address': request.term}, function(results, status) { //отправляем введенный текст response($.map(results, function(item) { //и получаем список возможных вариантов адресов return { //какую мы и генерируем в объект для autocomplete label: item.formatted_address, value: item.formatted_address, latitude: item.geometry.location.lat(), longitude: item.geometry.location.lng() }; })); }); }, select: function(event, ui) { //в случае выбора некого пункта var layer = OpenLayersMap.getLayersByName('Geocoder')[0]; layer.removeAllFeatures(); //очищаем слой от предыдущих объектов var point_popup = new OpenLayers.LonLat(ui.item.longitude, ui.item.latitude); //создаем координаты для попапа point_popup.transform(new OpenLayers.Projection("EPSG:4326"), OpenLayersMap.getProjectionObject()); //и переводим в другую проекцию var point = new OpenLayers.Geometry.Point(ui.item.longitude, ui.item.latitude); //создаем точку point.transform(new OpenLayers.Projection("EPSG:4326"), OpenLayersMap.getProjectionObject()); var feature = new OpenLayers.Feature.Vector(point); //создаем объект точки var popup = new OpenLayers.Popup.FramedCloud('geocoder_marker', point_popup, new OpenLayers.Size(200, 50), ui.item.label, null, false, true); //создаем попап OpenLayersTools.BaseFunc.CenterMap(ui.item.longitude, ui.item.latitude, 'EPSG:4326'); //центрируем на координатах адреса popup.closeOnMove = true; //выставляем свойство, при движении карты закрыть попап OpenLayersMap.addPopup(popup); layer.addFeatures(feature); //и добавляем все это на карту и слой } });
Full code need not even hang it from the top and so all :)
PS I tried to write it here, I do not know, it came out or not. But still waiting for constructive criticism, suggestions :)
0 commentaires:
Enregistrer un commentaire