This is the 9th day of my participation in the More text Challenge. For details, see more text Challenge

This article is participating in the “Java Theme Month – Java Development in action”. See the link to the event for more details

GeoJSON is a format for encoding various geographic data structures.

Introduction: In the last two weeks I have taken you through the key steps in WebGisTiles to load+Click on the event(See the previous two articles for details.) Next, I’ll take you through the loading of Geojson and its click events

  • Geojson data parsing

GeoJSON is a format for encoding various geographic data structures. A GeoJSON object can represent a geometry, a feature, or a collection of features. GeoJSON supports the following geometric types: point, line, plane, multipoint, multiline, multiface, and geometric collection. A feature in GeoJSON contains a geometric object and other properties, and a feature set represents a set of features.

A complete GeoJSON data structure is always an object (in JSON terms). In GeoJSON, an object consists of a collection of name/value pairs, also known as members. The name is always a string for each member. The value of a member is either a string, number, object, array, or one of the following text constants: “True “,”false”, or” NULL “. Arrays are made up of the elements whose values are described above.

GeoJSON collection features:

{" type ":" FeatureCollection ", "the features" : [{" type ":" Feature ", "id" : "001", "properties" : {" name ":" China 001 "}, "geometry":{"type": "Point", "coordinates" : [121.9850, 42.6737]}}, {" type ":" Feature ", "id" : "002", "properties" : {" name ":" China 002 "}, "geometry":{"type": "Point", "coordinates" : [121.8345, 42.4898]}}, {" type ":" Feature ", "id" : "003", "properties" : {" name ":" 1 peak mountain "}, "geometry":{"type": "LineString," "coordinates" : [[121.9850, 42.6737], [121.8345, 42.4898]]}}, {" type ":" Feature ", "id" : "004", "Properties" : {" name ", "China 1001"}, "geometry" : {" type ": "Point", "coordinates" : [128.9850, 42.6737]}}, {" type ":" Feature ", "id" : "005", "properties" : {" name ":" China 1002 "}, "geometry":{"type": "Point", "coordinates" : [125.8345, 42.4898]}}, {" type ":" Feature ", "id" : "006", "properties" : {" name ":" mountain 2 "}, "Geometry" : {" type ":" LineString, "" coordinates" : [[121.9850, 42.6737], [125.8345, 42.4898]]}}}]Copy the code

  • Openlayers3 code is loaded

    As for how to load a map, I already mentioned loading a tile map in the first article. After reading the first article, you should know that I transferred the map map to the div of the page, and the map contains many mask layers. Now I load GeoJSON by loading the URL data on the top layer.

var vector = new ol.layer.Vector( { source : new ol.source.Vector( { // url: / / 'http://openlayers.org/en/v3.17.1/examples/data/geojson/countries.geojson', url: ". / source/China. Json ', the format: new ol.format.GeoJSON() }), style : selectStyleFunction });Copy the code

I prepared this is reference to local data (can be gained from the server and from the server only need url rewrite into service address), after completion of loading url will not be displayed in the map, we also need to specify the data display, and tiles before here is load is different, the style is very important to me to adjust for a long time to adjust the, I’m going to encapsulate it in a method.

Method implementation:

var style; if(feature.getGeometry().getType()=="Point"){ style = [new ol.style.Style({ image : new ol.style.Circle( { fill : New ol.style.fill ({color: 'rgba(255,255,0,0.4)'}), radius: 2, stroke: new ol.style.fill ({color: 'rgba(255,255,0,0.4)'}), radius: 2, stroke: new ol.style.stroke ({color: 'black', width : 1 }) }), text : new ol.style.Text( { fill : textFill, stroke : textStroke, text : view.getZoom()>5?(feature.getId()>2?feature.get("name"):""):"" }) })]; }else if(feature.getGeometry().getType()=="LineString"){ if(view.getZoom()<3){ return ; } style = [new ol.style.Style( { stroke : new ol.style.Stroke( { color : '#CD950C', width : 2 }), text : new ol.style.Text( { fill : textFill, stroke : textStroke, text : view.getZoom()>6?feature.get("name"):"" }) })]; }else if(feature.getGeometry().getType()=="Polygon"){ style = [new ol.style.Style( { stroke : new ol.style.Stroke( { color : '#FFE4B5', width : 3 }), text : new ol.style.Text( { fill : textFill, stroke : textStroke, text : feature.get("name") }) })]; }else if(feature.getGeometry().getType()=="MultiLineString"){ style = [new ol.style.Style( { stroke : new ol.style.Stroke( { color : 'black', width : 3 }) })]; } return style;Copy the code

Some of the parameters in the declaration are not declared, because global variables are defined, because the previous js changes, so not all of the code is posted. Here needs the complete code please CSDN private message me or in the message board


  • Effect of appreciation

    The map you see here is not the last one. This time, it is the data in GeoJSON, but the data is shown in a graphical form in front of us. Do you see the two points and a line on the upper right of the map? I just need to change the data in the GeoJSON to make the map different, which makes it easy to change the map in the background. And the Framework of China is also from the data. In a word, all the elements you see in this map are set in the data (except the style).

2, zoom in on the map, and as before, it is worth noting that I set up in the js show level, is the data according to different level of zoom is also different, for example, the line, I set up in level 6 or more to see, I narrowed the map below line was gone, here are gone and not too look down upon

3, in zoom to a certain level I set the point around the point to show the name of the point! See the effect

So here’s the effect of loading, so let’s move on. Now click events, which IN the last article I focused on the principle and implementation of the click events, in the new technology we are Easy to click events


  • Click on the event

We want to bind events in the map, that is, register events

map.on('singleclick', mapClick);
Copy the code
function mapClick(e) { var pixel = map.getEventPixel(e.originalEvent); var featureInfo = map.forEachFeatureAtPixel(pixel, function(feature, layer) { return { feature : feature, layer : layer }; }); var coordinate = e.coordinate; var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326')); if (featureInfo ! == undefined && featureInfo ! == null && featureInfo.layer ! == null) { if (featureInfo.feature.get("geometry").B.length == 2) { // alert(view.getZoom()); Alert (HDMS + "featureinfo.feature.get ("name") + featureinfo.feature.get ("name") + featureFeature.feature.get ("name")); } else if (featureinfo.feature.get ("geometry").b.length == 4) {alert(HDMS + "\n ") + featureinfo.feature.get ("name") featurefeature.feature.get ("geometry").b.length == 4) {alert(HDMS + "\n ") + "line"); Alert (" 资 讯 "+ Featureinfo.feature.get (" Geometry ").b); } else {/ / alert (HDMS + "\ n here belong to" + featureInfo. Feature. The get (" name ") + "province"); } console.log(' print the selection element '); console.log(featureInfo.feature); Console. log(' Print the Layer to which the selection element belongs '); console.log(featureInfo.layer); } else {alert(HDMS + "\n this is not China or this is the sea "); // Display the click area}}Copy the code

Here I need to explain:

Featureinfo.feature.get (“geometry”).b.length == 2 featureinfo.feature.feature.get (“geometry”).b.length == 2 FeatureInfo.feature.feature.get (“geometry”).b.length == 2 FeatureFeature.feature.feature.get (“geometry”).b.length == 2 FeatureFeature.feature.feature.get (“geometry”).b.length == 2 You think if there are two Numbers point is point is, if the line is two points, that is, four Numbers, if is the area that is at least is even more than 4, so that we can distinguish the point, line and area, that is to say we’ve achieved before here hard to solve the problem of point, line, area we would not have more discussion on the problem.

var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(coordinate,'EPSG:3857', 'EPSG:4326'));
Copy the code

This is the transformation of coordinates, and I won’t talk about that


  • positioning

    In the past we used to have a positioning in the center of a point with an icon and that was what we called positioning, so does positioning change in our new technology? Let’s find out.

If you think that because it is a new technology, there must be a breakthrough, then my answer may disappoint you. The new technology still uses the above ideas to achieve the positioning, but it is more or less different.

| | new contrast openlayers2 | openlayers3 | | : -- -- -- -- -- -- -- -- -- -- -- -- -- - | : -- -- -- -- -- -- -- -- -- -- -- -- - | : -- -- -- -- - | | | click for latitude and longitude check out distinguish | | point line category showed | | | positioning map center Show | view centerCopy the code

As you can see from the table above, our positioning is different. In the new technology, we can use the View center display method. What is the view center display method?

view.setCenter(ol.proj.fromLonLat( [

Number(document.getElementById('jd').value),

Number(document.getElementById('wd').value) ]));
Copy the code

  • This section describes other common events

Event handlers

One of the new features in HTML 4.0 is the ability to have HTML events trigger actions in the browser, such as launching a piece of JavaScript when a user clicks on an HTML element. Below is a list of attributes that can be inserted with HTML tags to define event actions.

Specific events

attribute This event occurs when the following occurs FF N IE
onabort Image loading is interrupted 1 3 4
onblur Element out of focus 1 2 3
onchange The user changed the contents of the domain 1 2 3
onclick Mouse clicks on an object 1 2 3
ondblclick Double-click on an object 1 4 4
onerror An error occurred while loading a document or image 1 3 4
onfocus Element gets focus 1 2 3
onkeydown The key of a certain keyboard is pressed 1 4 3
onkeypress Keys of a keyboard are pressed or held down 1 4 3

Refer here to w3School

I just added a few random ones to my map to try them out.

var select = null; // ref to currently selected interaction // select interaction working on "singleclick" var selectSingleClick = new ol.interaction.Select(); // select interaction working on "click" var selectClick = new ol.interaction.Select( { condition : ol.events.condition.click }); // select interaction working on "pointermove" var selectPointerMove = new ol.interaction.Select( { condition : ol.events.condition.pointerMove }); var selectAltClick = new ol.interaction.Select( { condition : function(mapBrowserEvent) { return ol.events.condition.click(mapBrowserEvent) && ol.events.condition.altKeyOnly(mapBrowserEvent); }}); var selectElement = document.getElementById('type'); var changeInteraction = function() { if (select ! == null) { map.removeInteraction(select); } var value = selectElement.value; if (value == 'singleclick') { select = selectSingleClick; } else if (value == 'click') { select = selectClick; } else if (value == 'pointermove') { select = selectPointerMove; } else if (value == 'altclick') { select = selectAltClick; } else { select = null; } if (select ! == null) { map.addInteraction(select); select.on('select', function(e) { document.getElementById('status').innerHTML = '&nbsp; ' + e.target.getFeatures().getLength() + ' selected features (last operation selected ' + e.selected.length + ' and deselected ' + e.deselected.length + ' features)'; }); }};Copy the code

Here the whole GeoJSON loading map has been explained, the above is just to help you tease out ideas, not the complete code of the project, if the new entry did not understand, you can leave a comment in the blog below, I will send the source code to you.