OpenLayers with Google Maps simple tutorial

what is openlayer

OpenLayers is a high performance and comprehensive map library. Has the following features:

  1. Supports various formats of Tiled Layers data
  2. Using Canvas’ high-performance Vector Layer
  3. Fine-grained and rich interactions
  4. The Commanjs style is supported
  5. Free open source

why use it

In general, the Google Map API will do the job, but when you need to draw a lot of nodes on a map, using SVG to display widgets can cause serious performance problems, and editing operations like Google Maps are generally not smooth enough. However, OpenLayers uses Canvas as the vector layer, so a large amount of point, line and surface information has little impact on Canvas, and the interaction between Canvas is more smooth.

why write this article

  1. With AutoNavi Maps, Google Maps, Baidu Maps and other commonly used domestic map does not have a very convenient interface
  2. The official documentation is incomplete and unclear after the major update, and there is no guild
  3. And there are few concise and detailed tutorials online

In view of the above points, I think my little experience will be helpful to you, you can take less detours, and it is also a summary of my work in these days.

a simple example(step by step)

Here’s a quick example of some of the basic uses of OpenLayers and what I find important.

demand

You need to use Google Map or Automap as the base map, draw a rectangle on the map, realize the editing of the rectangle and get the callback function after the rectangle is modified. These are the technical points that might be involved:

  1. How to combine with Google Map and other maps
  2. How to add feature to map if you know coordinate array or GEO data in a certain format
  3. Complete the modification of the feature
  4. The callback method of the modified feature is obtained

Attached is a simple screenshot

Initialize the map

We want OpenLayer to be used in combination with Google Map, etc., but since Google and other map vendors are not willing to “compromise” with OpenLayer, we can’t use Tled Layers directly now, but we can use OpenLayer in combination with the map API.

Only use the base map of the map, cover the base map with a Canvas layer of OpenLayer to display the data and intercept the interaction with the base map, and reset the state through the API of the map. This scheme also has the following advantages:

  1. Solve the performance problem after too many page nodes
  2. Base maps can be abstracted away and can be replaced without affecting the interaction logic.

The code is as follows:

html<! DOCTYPE html> <html> <head> <title>Snap interaction example</title> <script SRC = "https://code.jquery.com/jquery-1.11.2.min.js" > < / script > < link rel = "stylesheet" Href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" > < script SRC = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" > < / script > < link rel = "stylesheet" Href = "https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.css" type = "text/CSS" > < script SRC = "https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.js" > < / script > < script src="https://maps.googleapis.com/maps/api/js"></script> <style type="text/css"> div.fill { width: 100%; height: 100%; } .map { width: 800px; height: 400px; } </style> </head> <body> <div class="container-fluid"> <div class="row-fluid"> <div class="span12"> <div id="map" class="map"> <! Gmap is used to load Google Maps and olmap is used to load OpenLayer Canvas. The goal is for olmap to override gmap and intercept interactions after loading. The advantage of starting on the same layer is that you can set the length and width based on the parent node. You can also dynamically generate divs in JS, Rendering after insert - > < div id = "gmap" class = "fill" > < / div > < div id = "olmap" class = "fill" > < / div > < / div > < / div > < / div > < / div > < script Var gmap = new Google.maps.map (document.getElementById('gmap')); var gmap = new Google.maps.map (document.getElementById('gmap'));  { disableDefaultUI: true, keyboardShortcuts: false, draggable: false, disableDoubleClickZoom: true, scrollwheel: false, streetViewControl: false }); // ol.View is the object that OpenLayers uses to control the map's coordinate system standard zoom center rotate, etc. View({// Make sure the view doesn't go beyond the 22 Zoom levels of Google Maps // It is set to the standard coordinates of longitude and latitude. It is made by projection: 'EPSG '// Default is 'EPSG:3857'}); // When the view is dragged, it triggers an event that is converted to latitude and longitude based on the current coordinate. On ('change:center', function () {var center = view.getCenter(); gmap.setCenter(new google.maps.LatLng(center[1], center[0])); // Note the order}); View. On (' Change: Resolution ', function () {gMap.setZoom (View.getZoom ()); }); Var vectorSource = new ol.source.vector (); var vectorSource = new ol.source.vector (); var vector = new ol.layer.Vector({ source: vectorSource }); var olMapDiv = document.getElementById('olmap'); Var map = new ol. map ({layers: [vector], // Disable Drag, Rotate and Interactions by default: ol.interaction.defaults({ altShiftDragRotate: false, dragPan: false, rotate: false }).extend([new ol.interaction.DragPan({kinetic: null})]), target: olMapDiv, view: View({options}) but in this case you need to set it manually to trigger the Google Maps adjustment to the correct Zoom and Center}); The setCenter ([10.689697265625, 25.0927734375]); // If you don't set the view's coordinate standard, be sure not to write view.setZoom(6); / / set the zoom level / / place openlayers container to Google map container olMapDiv. ParentNode. RemoveChild (olMapDiv); gmap.controls[google.maps.ControlPosition.TOP_LEFT].push(olMapDiv); </script> </body> </html>

With this code you should have a map that you can zoom in and out of.

To add a feature

Of course, it is not enough to only have a map. If we need to add feature to the map, what should we do? There are generally two scenarios as follows:

  1. Providing the entire map information description data, such as GeoJSON, WKT or custom data structure, needs to parse the entire data and bulk display on the map.
  2. When the coordinate data of a feature is obtained, it needs to be added to the map and the control of special alienation is realized.

Batch add data

On the first code

javascript/** * Add the GeoJSON string to the map * @Param VectorSource {ol.source.vector} GeoJson string * / function addFeatures (vectorSource, data) {vectorSource. AddFeatures (ol) format. GeoJson. ReadFeatures (data, {// Data Projection: 'EPSG:3857', // Map View: FeatureProjection: 'EPSG:4326'}); }

There are many types of data in ol.format. Select the data format to match. Such as the WKT use ol. Format. WKT. ReadFeature

ReadFeature returns an array of ol. features, which can be traverse to obtain Feature objects, so as to modify or mount listening events as required.

Add a single feature

If the existing data is in a standard format such as GeoJSON, you can convert it using classes in ol.format. If there is a need, use ol.proj.transform to transform the coordinate system.

Var / / return a single feature object feature = ol. Format. GeoJSON. ReadFeature (data) / / added to the source vectorSource. AddFeature (feature);

If you’re getting latitude and longitude information, add a polygon

// Data is a two-dimensional array of Coordinates. Note that the var feature = new ol.feature(new ol.geom.polygon (data));

Modify the feature

Describes how to modify the Feature and mount listener events.

Initialize the change add, change interaction

Var select = new ol.interaction.Select({// select filter from feature Editable option: function(feature) { if (_this._featureMap[feature.getId()].editable) { return true; }}}); Var selected = select.getFeatures(); var selected = select.getFeatures(); Feature var modify = new ol.interaction.Modify({features: selected}); Select. On ('add', event => {var feature = event.element}); Select. On ('remove', evt => {var feature = evt.element; var fid = feature.getId(); // Change event to determine if the feature is modified or needs to be featured console.log(FID); }); // Add this._map = new ol.Map({layers: [vector], interactions: ol.interaction.defaults({ altShiftDragRotate: false, dragPan: false, rotate: false }).extend([new ol.interaction.DragPan({kinetic: null}), select, modify]), target: $olMapDiv, view: this._view });

In general, if you need to conduct subsequent operation on the feature, you can use getId method to get the ID of the feature. You can set the desired ID through setId, otherwise it will be generated automatically. Store the ID in a resident object for later use.

Suppose you get the ol.Feature object Feature

feature.on('change:geometry', function(e){ var feature = e.element; // do what you want for example the symbol has been modified})

Note that this onChange event will be triggered during the modification process. If you want a callback after the modification is complete, use the select remove event.

select.getFeatures().on('remove', function(e){})

Modify the Feature Object

Set the id

feature.setId(id)

Get the Geometry object

var geometry = feature.getGeometry(); // Modify the symbol coordinates by calling methods of the Geometry class

feature to string

var format = new ol.format.GeoJSON();
format.writeFeature(feature);

Something to watch out for

  • The default coordinate system for OpenLayers is'EPSG:3857'The standard latitude and longitude coordinate system is'EPSG:4326'
  • The most important trick to look at OpenLayer documents is to pay attention to types
  • Coordinates accepted by the Geometry is actually a three-dimensional array, so you have to be aware of that

Common operations

Coordinate system transformation

Convert the current coordinate system to the target coordinate system.

Ol.proj.transform (Coordinate, Source, Destination) coordinate and that’s what you get in your document is called a coordinate which is essentially an array of horizontal and vertical coordinates, so make sure you pay attention to what type of data you get in your official document. Destination The destination code for the source is string

Converts from latitude and longitude to a specified coordinate system

Ol.proj. fromLonLat(coordinate, opt_projection) opt_projection

From some coordinate to latitude and longitude

ol.proj.toLonLat(coordinate, opt_projection)

Data formatting

ol.format