Solve the problem of OpenLayers 3 loading vector map source

Solve the problem of OpenLayers 3 loading vector map source

1. Vector Map

Vector graphics use straight lines and curves to describe graphics. The elements of these graphics are points, lines, rectangles, polygons, circles, arcs, etc., which are all obtained by calculating mathematical formulas. Since vector graphics can be obtained through formula calculation, the file size of vector graphics is generally small. The biggest advantage of vector graphics is that they will not be distorted no matter they are enlarged, reduced or rotated. There are a large number of applications in maps, which is a very important component of map data.

In order to facilitate storage, transmission and use, vector maps are expressed in certain formats, such as the common GeoJSON , TopoJSON , GML , KML , ShapeFile , etc. In addition to the last ShapeFile , OpenLayers 3 supports several other vector map formats.

2. Loading vector maps using GeoJson format

1. Project Structure

2. map.geojson

{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[104.08859252929688,30.738294707383368],[104.18060302734375,30.691068801620155],[104.22042846679688,30.739475058679485],[104.08859252929688,30.738294707383368]]]}},{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[104.08859252929688,30.52323029223123],[104.08309936523438,30.359841397025537],[104.1998291015625,30.519681272749402],[104.08859252929688,30.52323029223123]]]}},{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[103.70269775390624,30.675715404167743],[103.69308471679688,30.51494904517773],[103.83316040039062,30.51494904517773],[103.86474609375,30.682801890953776],[103.70269775390624,30.675715404167743]]]}}]}

3. map.html

<!Doctype html>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
    <meta content='always' name='referrer'>
    <title>OpenLayers 3: Loading vector maps</title>
    <link href='ol.css ' rel='stylesheet' type='text/css'/>
    <script type='text/javascript' src='ol.js' charset='utf-8'></script>
</head>

<body>

<div id='map' style='width: 1000px;height: 800px;margin: auto'></div>

<script>

    /**
     * Create a map */
    new ol.Map({

        // Set the map layers layers: [

            //Create a layer that uses the Open Street Map map source new ol.layer.Tile({
                source: new ol.source.OSM()
            }),

            //Load a geojson vector map new ol.layer.Vector({
                source: new ol.source.Vector({
                    url: 'geojson/map.geojson', // Map source format: new ol.format.GeoJSON() // Formatting class for parsing vector maps})
            })

        ],

        // Set the view to display the map view: new ol.View({
            center: [104,30], // Set the map display center to longitude 104 degrees and latitude 30 degrees zoom: 10, // Set the map display level to 10
            projection: 'EPSG:4326' //Set projection}),

        // Let the div with id map be the container of the map target: 'map'

    })

</script>
</body>
</html>

4. Operation results

3. Get all features on the vector map and set the style

1.map2.html

<!Doctype html>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
    <meta content='always' name='referrer'>
    <title>OpenLayers 3: Get all features on the vector map and set the style</title>
    <link href='ol.css ' rel='stylesheet' type='text/css'/>
    <script type='text/javascript' src='ol.js' charset='utf-8'></script>
</head>

<body>

<div id='map' style='width: 800px;height:500px;margin: auto'></div>
<br>
<div style='width: 800px;margin: auto'>
    <button type="button" onclick = 'updateStyle()' >Modify Feature style</button>
</div>

<script>

    /**
     * Create a map */
    var map = new ol.Map({

        // Set the map layers layers: [
            //Create a layer that uses the Open Street Map map source new ol.layer.Tile({
                source: new ol.source.OSM()
            }),
        ],

        // Set the view to display the map view: new ol.View({
            center: [104,30], // Set the map display center to longitude 104 degrees and latitude 30 degrees zoom: 10, // Set the map display level to 10
            projection: 'EPSG:4326' //Set projection}),

        // Let the div with id map be the container of the map target: 'map'
    });

    //Create a vector map source layer and set the style var vectorLayer = new ol.layer.Vector({
            source: new ol.source.Vector({
                url: 'geojson/map.geojson', // Map source format: new ol.format.GeoJSON() // Formatting class for parsing vector maps}),
            // Set the style, color is green, line thickness is 1 pixel style: new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'green',
                    size: 1
                 })
            })
        });


    map.addLayer(vectorLayer);


    /**
     * Get all the features on the vector layer and set the style */
    function updateStyle(){

        //Create a style with red color and 3 pixel line thickness var featureStyle = new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'red',
                size: 3
            })
        })

        //Get all the features on the vector layer
        var features = vectorLayer.getSource().getFeatures()


        //Traverse all Features and set the style for each Feature for (var i = 0; i < features.length; i++) {
            features[i].setStyle(featureStyle)
        }


    }


</script>
</body>
</html>

2. Operation results

4. Vector map coordinate system conversion

Vector maps use EPSG:4326 . We can use the built-in map format parser in OpenLayers 3 to convert coordinates to EPSG:3857

1.map3.html

<!Doctype html>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
    <meta content='always' name='referrer'>
    <title>OpenLayers 3: Vector map coordinate system conversion</title>
    <link href='ol.css ' rel='stylesheet' type='text/css'/>
    <script type='text/javascript' src='ol.js' charset='utf-8'></script>
    <script src="jquery-3.6.0.js"></script>
</head>

<body>

<div id='map' style='width: 1000px;height: 800px;margin: auto'></div>

<script>

    /**
     * Create a map */
    var map = new ol.Map({

        // Set the map layers layers: [

            //Create a layer that uses the Open Street Map map source new ol.layer.Tile({
                source: new ol.source.OSM()
            })
        ],

        // Set the view to display the map view: new ol.View({
            center: ol.proj.fromLonLat([104,30]), // Set the map display center at longitude 104 degrees and latitude 30 degrees zoom: 10, // Set the map display level to 10
        }),

        // Let the div with id map be the container of the map target: 'map'

    });


    // Load vector map function addGeoJSON(data) {
        var layer = new ol.layer.Vector({
            source: new ol.source.Vector({
                features: (new ol.format.GeoJSON()).readFeatures(data, { // Use the readFeatures method to customize the coordinate system dataProjection: 'EPSG:4326', // Set the coordinate system used by the JSON data featureProjection: 'EPSG:3857' // Set the coordinate system of the feature used by the current map })
            })
        });
        map.addLayer(layer);
    };


    $.ajax({
        url: 'geojson/map.geojson',
        success: function(data, status) {
            // After successfully obtaining the data content, call the method to add the vector map to the map addGeoJSON(data);
        }
    });

</script>
</body>
</html>

2. Operation results

This is the end of this article about OpenLayers 3 loading vector map source. For more information about OpenLayers 3 loading vector map, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of map overlay in openlayers6
  • Three common uses of openlayers6 map overlay (popup window marker text)
  • Openlayers draws map annotations

<<:  Specific use of MySQL operators (and, or, in, not)

>>:  Introduction to partitioning the root directory of Ubuntu with Vmvare virtual machine

Recommend

Practical basic Linux sed command example code

The Linux stream editor is a useful way to run sc...

What are the benefits of using // instead of http:// (adaptive https)

//Default protocol /The use of the default protoc...

How to install mysql in docker

I recently deployed Django and didn't want to...

Problem record of using vue+echarts chart

Preface echarts is my most commonly used charting...

15 Vim quick reference tables to help you increase your efficiency by N times

I started using Linux for development and enterta...

Ideas and practice of multi-language solution for Vue.js front-end project

Table of contents 1. What content usually needs t...

JS version of the picture magnifying glass effect

This article shares the specific code of JS to ac...

Docker Swarm from deployment to basic operations

About Docker Swarm Docker Swarm consists of two p...

How to Apply for Web Design Jobs

<br />Hello everyone! It’s my honor to chat ...

How to convert mysql bin-log log files to sql files

View mysqlbinlog version mysqlbinlog -V [--versio...

Understanding of web design layout

<br />A contradiction arises. In small works...

Vue state management: using Pinia instead of Vuex

Table of contents 1. What is Pinia? 2. Pinia is e...

Common HTML tag writing errors

We better start paying attention, because HTML Po...

HTML table tag tutorial (34): row span attribute ROWSPAN

In a complex table structure, some cells span mul...