Getting a vector layer from JSON in OpenLayers 3 can be achieved by following these steps

Below is the script where I have included vector layers vectorLayer, vectorLayer5, vectorLayer1

How can I retrieve that layer from JSON.. I want to add multiple layers from an external JSON file with the icon PNG image

// Updated on input change
var radius = 10;
  longitude = 400000;
  latitude = 300000;


var styleFunction = function() {
  return new ol.style.Style({
    image: new ol.style.Circle({
      radius: radius,
      stroke: new ol.style.Stroke({
        color: [51, 51, 51],
        width: 2
      }),
      fill: new ol.style.Fill({
        color: [51, 51, 51, .3]
      })
    })
  });
};

var update = function(value) {
var wgs84Sphere = new ol.Sphere(6378137);
  radius = value;
  vectorLayer.setStyle(styleFunction);
 if(wgs84Sphere.haversineDistance(feature.getGeometry().getCoordinates(),iconFeature5.getGeometry().getCoordinates())<=radius){
      vectorLayer5.setVisible(true);
      console.log('a');
  }
  else{
      vectorLayer5.setVisible(false);
      console.log('b');
  }
}

var feature = new ol.Feature(new ol.geom.Point([longitude, latitude]));
var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [feature]
  }),
  style: styleFunction
});
 var rasterLayer = new ol.layer.Tile({
   source: new ol.source.TileJSON({
     url: 'http://api.tiles.mapbox.com/v3/mapbox.geography-class.json',
     crossOrigin: ''
   })
 });

// icon marker start here

var iconFeature5 = new ol.Feature({
  geometry: new ol.geom.Point([longitude, latitude]),
  name: 'Missing Person',
  population: 4000,
  rainfall: 500
});

var vectorSource5 = new ol.source.Vector({
  features: [iconFeature5]
});

var vectorLayer5 = new ol.layer.Vector({
  source: vectorSource5
});

var iconStyle5 = new ol.style.Style({
  image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
    anchor: [0.5, 46],
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    
    src: 'https://cloud.githubusercontent.com/assets/41094/2833021/7279fac0-cfcb-11e3-9789-24436486a8b1.png'
  }))
});
iconFeature5.setStyle(iconStyle5);

// 2nd marker

  longitude1 = 100000;
  latitude1 = 100000;
var iconFeature1 = new ol.Feature({
  geometry: new ol.geom.Point([longitude1, latitude1]),
  name: 'Missing Person',
  population: 4000,
  rainfall: 500
});

var vectorSource1 = new ol.source.Vector({
  features: [iconFeature1]
});

var vectorLayer1 = new ol.layer.Vector({
  source: vectorSource1
});

iconFeature1.setStyle(iconStyle5);



var map = new ol.Map({
  layers: [rasterLayer,vectorLayer,vectorLayer5,vectorLayer1],
  target: document.getElementById('map'),
  view: new ol.View({
    center: [400000, 400000],
    zoom: 4
  })
});
html, body, #map {
  height: 100%;
  overflow: hidden;
}
.input {
  margin: 5px 0;
}
<script src="http://openlayers.org/en/v3.16.0/build/ol.js"></script>

<div class="input">
  <input type="range" id="range" min="10" max="50" onchange="update(this.value)">
  <input type="text" id="range" value="10">
</div>
<div id="map" class="map"></div>

Answer №1

When working in web mapping, JSON data with geometries is referred to as GeoJSON and typically has its own extension in text files. To incorporate a GeoJSON file into an OL3 map, you must first load it into the vector source of the layer. Below is a snippet of code demonstrating how to load an external GeoJSON file into an OL3 map:

var vectorSource = new ol.source.Vector({
      projection: 'EPSG:4326', // or 'EPSG:8357'
      url: 'yourExternalFile.geojson',
      format: new ol.format.GeoJSON()
});
var vectorLayer = new ol.layer.Vector({
    title: 'geojson layer',
    source: vectorSource,
    style: new ol.style.Style({
        image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
            anchor: [0.5, 0],
            anchorOrigin: 'bottom-left',
            anchorXUnits: 'fraction',
            anchorYUnits: 'pixels',
            src: 'yourImage.png'
        }))
    })
});

Note: OpenLayers 3 website provides helpful examples that can be combined with this code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for integrating html2canvas with Vue JS?

One hurdle I encountered was the absence of a shorthand for document.getElementById in Vue. To address this, I created a custom function similar to this one. Another challenge I am currently grappling with is the perceived limitations of the html2canvas do ...

Mastering the Art of Sending Multiple Values via Ajax

I'm having trouble passing multiple values using ajax in my code snippet. Here is the code I am working with: $(".ajax-button").change(function(event){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': '{{ ...

Converting a sophisticated PHP object into a JSON string

I'm struggling with parsing a complex object in PHP to create a Json String. Despite searching through various examples online, none of them seem to work for me. To add to the challenge, my hosting platform only supports PHP 5.2 and I cannot upgrade i ...

An issue arises with the Datatables destroy function

Utilizing datatables.js to generate a report table on my page with filters. However, when applying any of the filters, the data returned has varying column counts which prompts me to destroy and recreate the table. Unfortunately, an error message pops up ...

My goal is to generate four HTML buttons that trigger specific functions: addition, subtraction, multiplication, and division

I am currently learning JavaScript, and I am facing some challenges with my assignment. The task is to create four buttons in HTML that trigger different functions - addition, subtraction, multiplication, and division. The goal is for the user to input two ...

How do I use regex to grab all the text between two specific headers?

I need help extracting text between two specific headings. I attempted to create a regex for this purpose, but it's not quite capturing what I want. Currently, it includes the heading and paragraph, but misses the last heading. My Current Regex: /^& ...

Unraveling nested elements with the array map() method in Angular2 and Typescript: Fixing the issue of undefined property reference while mapping

Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and &apo ...

What is the correct way to add an object to a specific array in express.js?

My goal in the following function is to write a JSON file with an array of data as strings. However, the push() function, which is commented out, is causing the code to not execute as intended. Everything works fine without that line of code, but I do need ...

Display or conceal div based on chosen options

I am working on a feature that involves three dropdown select boxes, each containing different sets of demographic attributes. My goal is to show a score based on the combination of selections made by the user. For example, if a user chooses Male, 18-24, A ...

What to do when your Numpy array exceeds RAM capacity: Store to disk or use an out-of-core approach?

In my workflow, I have a process where I add data to an initial pandas Series object. This empty array could also be a NumPy array, or a simple list. in_memory_array = pd.Series([]) for df in list_of_pandas_dataframes: new = df.apply(lambda row: comp ...

When a URL is entered, information is not retrieved from the database

I have a simple app setup where the data (iPhones from the database) is fetched in the AppComponent itself. ngOnInit(): void { this.iphoneservice.fetchIphones(); } The fetchIphones method is located in my iPhoneService file and consists of 3 functio ...

Can you specify the third argument sent to the listener?

Recently I delved into exploring the capabilities of the d3 framework. One thing that caught my attention was the presence of a third parameter in the event listener for v3. Despite always being 0, I couldn't find any explanation on its intended purpo ...

What is the best way to incorporate a @types module into a TypeScript file that is not already a module?

Setting the Stage: In the process of shifting a hefty ~3,000 line inline <script> from a web-page to a TypeScript file (PageScripts.ts) to be utilized by the page through <script src="PageScripts.js" defer></script>. This script entails ...

Refresh a div with Ajax once all data has been fully loaded

I am currently using an ajax refresh div function that reloads a specific div every 10 seconds. Occasionally, the div loads before receiving data from mysql. Is there a way to modify it so that it waits 2 seconds after reloading the div? <script type ...

Parse the JSON data into a Dictionary with string keys and object values

As a beginner in C# and JSON, I recently encountered a JSON file with the following structure: {"person1":[{"name":"Bobby"},{"age":25},{"height":178},{"hobby":"piano"}],"person2":[{"name":"Tyler"},{"age":29},{"height":185}, ,{"hobby":"basketball"}],"perso ...

Issue with ASP.NET Core Controller not properly receiving complete JavaScript array object from Ajax call

When passing a JavaScript Object Array through ajax to the controller, I noticed that if there are more than 11 objects in the array, the controller receives it as null. However, with 11 or fewer objects, the array is received successfully. Here is an exam ...

What is the best way to apply a class for styling my JavaScript code in CSS? I'm having trouble getting classList

I am having trouble adding a class to my JavaScript script in order to animate the images created in JavaScript to fall off the page. I have tried using the code element.classList.add("mystyle");, but every time I insert it, my JavaScript stops working. T ...

Update Button Colour upon clicking the Button

I have multiple buttons lined up in a row on my webpage. I want the button's color to change when I click on them. Below is a snippet of my code: $( "button.change" ).click(function() { $(this).toggleClass( "selected" ); }); .Button { font-fa ...

Customize chrome's default shortcuts with JavaScript

I'm working on an application that requires me to override some shortcut keys in the Chrome browser. While I'm able to create custom shortcuts to trigger alerts like in this Stackblitz example, I'm having trouble overriding a few default sho ...

While my other function remains incomplete, AngularJS $http continues to run without interruption

I'm facing an issue in my AngularJS function where the $http request is being fired before my first function is completed. Here's a sample of how my code looks: $scope.function = function(){ $scope.functionOne(); // This function initializ ...