Creating a circular shape around a specific location on a map is a common task in Openlayers. Here's a

I have been attempting to create a circle based on the point/coordinate where a user clicks. While I know how to generate a point and found a function that can create a circle based on said point (similar to a buffer or range ring), it appears to only function with x,y points at (0,0). After trying to convert my longitude and latitude coordinates to X and Y using ol.proj.transform, I was unsuccessful in rendering a circle at all.

Function to create circle

This is the desired outcome:

function createCircle(circleCenterX, circleCenterY, circleRadius, pointsToEnd) {
            let angleToAdd = 360 / pointsToEnd;
            let coords = [];
            let angle = 0;
            for (let i = 0; i < pointsToEnd; i++) {
                angle += angleToAdd;
                let coordX = circleCenterX + circleRadius * Math.cos(angle * Math.PI / 180);
                let coordY = circleCenterY + circleRadius * Math.sin(angle * Math.PI / 180);
                coords.push([coordX, coordY]);
            }
            return coords;
        }

        function addMarker(coordinates) {
            console.log(coordinates);
            var marker = new ol.Feature(new ol.geom.Point([708683.3598450683, 1850098.1965979263]));
            marker.setStyle(new ol.style.Style({
                image: new ol.style.Circle({
                    radius: 5,
                    fill: new ol.style.Fill({
                        color: 'red'
                    })
                })
            }));
            vectorSource.addFeature(marker);
        }

        function addCircle(coords) {
            // var lonlat1 = ol.proj.transform([coords[0], coords[1]], 'EPSG:4326','EPSG:3857');
            // console.log('var lonlat1',lonlat1)
            var circleCoords = createCircle(708683.3598450683, 1850098.1965979263, 20, 180);
            console.log(circleCoords);
            var polygon = new ol.geom.Polygon([circleCoords]);
            polygon.transform('EPSG:4326', 'EPSG:3857');
            polygon = new ol.Feature(polygon);
            vectorSource.addFeature(polygon);
        }

JsFiddle Link

Answer №1

The issue you are facing is that the addMarker function requires coordinates in the EPSG:3857 projection, whereas the addCircle function needs them in the EPSG:4326 projection.

If you wish to use the same coordinates for both functions, ensure they are standardized.

The reason the circle isn't displaying correctly at

[708683.3598450683, 1850098.1965979263]
is because those values are far beyond the map's limits (the maximum latitude value is 90 degrees).

addCircle(ol.proj.toLonLat([708683.3598450683, 1850098.1965979263]));
addMarker([708683.3598450683, 1850098.1965979263]);

Check out this updated fiddle with the same center point (but using different projections)

Snippet of the code used:

var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  view: new ol.View({
    center: ol.proj.fromLonLat([0, 0]),
    zoom: 3
  })
});
var layer = new ol.layer.Vector({
  source: new ol.source.Vector({
    projection: 'EPSG:4326',
    features: []
  }),
});
map.addLayer(layer);
var vectorSource = layer.getSource();

function createCircle(circleCenterX, circleCenterY, circleRadius, pointsToEnd) {
  let angleToAdd = 360 / pointsToEnd;
  let coords = [];
  let angle = 0;
  for (let i = 0; i < pointsToEnd; i++) {
    angle += angleToAdd;
    let coordX = circleCenterX + circleRadius * Math.cos(angle * Math.PI / 180);
    let coordY = circleCenterY + circleRadius * Math.sin(angle * Math.PI / 180);
    coords.push([coordX, coordY]);
  }
  return coords;
}

function addMarker(coordinates) {
  console.log(coordinates);
  var marker = new ol.Feature(new ol.geom.Point(coordinates));
  marker.setStyle(new ol.style.Style({
    image: new ol.style.Circle({
      radius: 5,
      fill: new ol.style.Fill({
        color: 'red'
      })
    })
  }));
  vectorSource.addFeature(marker);
}

function addCircle(coords) {
  var circleCoords = createCircle(coords[0], coords[1], 20, 180);
  console.log(circleCoords);
  var polygon = new ol.geom.Polygon([circleCoords]);
  polygon.transform('EPSG:4326', 'EPSG:3857');
  polygon = new ol.Feature(polygon);
  vectorSource.addFeature(polygon);
}

addCircle(ol.proj.toLonLat([708683.3598450683, 1850098.1965979263]));
addMarker([708683.3598450683, 1850098.1965979263]);
html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

.map {
  height: 100%;
  width: 100%;
}
<script src="https://openlayers.org/en/v6.4.3/build/ol.js"></script>
<link rel="stylesheet" type="text/css" href="https://openlayers.org/en/v6.4.3/css/ol.css" />
<div id="map" class="map"></div>

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

Using Blob to save CSV file on Safari

Here are the codes I am using to generate a download link for users to download a .csv file from my website. var link = document.createElement("a"); link.id = "csvDwnLink"; window.URL = window.URL || window.webkitURL; var csv = "\ufeff" + CSV, b ...

Having challenges retrieving information from MySQL in AngularJS

As a beginner in angularJS, I am trying to display all customers from MySQL. Here is the code I have written in the controller and service: app.controller('CustomersController', function ($scope, customersService, $http) { init(); function ini ...

What are some ways to display multiple divs within a single popup window?

I am attempting to create the following layout: Here is what I have been able to achieve: In the second picture, the divs are shown separately. My goal is to display the incoming data in a single popup like in the first picture, but I am having trouble a ...

What could be causing my Link to malfunction in my about.js file?

I've encountered an issue where clicking the link in my app doesn't produce any result, and I'm unsure of the cause. Below is the content of my app.js file: import './App.css'; import {BrowserRouter as Router, Routes, Route} from ...

When using the RxJs Pipe with MAP in Angular and Ionic, it may not return a value in windows, but it works perfectly in Mac when used with HttpClient

I'm currently using RxJs Pipe with Map for a network request in my Angular/Ionic project. Interestingly, while I do receive a successful response in the network log, the MAP function fails to return any value. Notable Observations Strangely, this fu ...

Tips for implementing events with AngularJS Bootstrap Colorpicker

I am having trouble understanding how events function with Angular Bootstrap Colorpicker. I have forked a Plunker from the developer's example. Unfortunately, there are no examples provided for using events. It would be great if events like colorpick ...

Encountering Err_Connection_Refused while working with MVC WebAPI 2 and AngularJS

Seeking guidance on WebAPI, AngularJS, and .NET Authentication, I am currently following a tutorial mentioned HERE. The tutorial is brief (~under 10 mins), but I encountered an error stating Failed to load resource: net::ERR_CONNECTION_REFUSED. Typically, ...

Use Jquery to retrieve the innerhtml content

Hey there! I'm currently in the process of learning Jquery and have encountered an issue with accessing form elements. My script is designed to open a div and then fill it with a predefined HTML form. To achieve this, I'm using ajax to fetch the ...

Having trouble getting my ReactJS page to load properly

I am currently linked to my server using the command npm install -g http-server in my terminal, and everything seems to be working smoothly. I just want to confirm if my h1 tag is functional so that I can proceed with creating a practice website. I have a ...

Set a variable to a specific cell within a table

I've been attempting to insert images into a table and have had success so far - clicking cycles through the available options. However, I've encountered an issue where the counter is not cell-specific but rather global. Is there a way to create ...

Utilizing jQuery's then() method to display HTML and JSON outputs from printing operations

Currently, I am in the process of mastering jquery deferreds. When working with html on jsfiddle, I receive an object that contains two lines when printed within the then() statement: "success" and the html returned by the ajax request. For instance, upo ...

Error message in React-router: Cannot read property 'func' of undefined, resulting in an Uncaught TypeError

When attempting to launch my react application, I encountered an error in the browser console: Uncaught TypeError: Cannot read property 'func' of undefined at Object../node_modules/react-router/lib/InternalPropTypes.js (InternalPropTypes.js: ...

AngularJS: Pause the data binding functionality temporarily

How can I temporarily deactivate data binding in AngularJS? I am working with a list called items that is being displayed using ng-repeat. I need to perform some operations on this list without immediately updating the page, as this could cause slowdown. ...

How can I convert a PHP date to a JavaScript date that works across all

I am attempting to create a JavaScript countdown timer that relies on the server time, but I'm facing difficulties in transferring PHP time to JavaScript seamlessly across different browsers. While it functions correctly in modern browsers, older ones ...

Strange issue: the code appears to be running multiple times with just one click

I've implemented a commenting system with a like feature. However, I'm facing an issue where sometimes clicking the like link results in sending multiple requests (up to 8-9) per click. This problem also occurs with another jQuery code that is tr ...

Ensuring continuous user login during webpage refreshes with the help of React and local storage

Currently, I am working on implementing the use of local storage to ensure that upon refresh, the user remains logged in rather than being signed out each time. Successfully, I have been able to store data in local storage by utilizing the following code ( ...

javascript Href and onclick malfunctioning

I am encountering an issue with a form on my webpage: <form name="myForm" id="myForm" method="post" action="someUrl.php"> ... </form> There is a div outside of this form which contains an anchor link: <a href="anotherUrl.php" onclick="doc ...

Issues with CSS properties not functioning correctly within the class.col function

When attempting to apply specific CSS properties to a particular area (e.g., "Dashboard") by assigning the class name "main" to the div.col function in the HTML, I encountered an issue where the CSS property applied affected the entire page. The following ...

jqRangeSlider experiencing performance issues in Chrome browser

Utilizing the jqRangeSlider on my website has been quite challenging. Strangely, when creating multiple instances of the slider, there is a significant delay in rendering on Google Chrome specifically (approximately 1.5-2 seconds for each slider out of 9). ...

Trigger a specific directive instance through a function call when a key is pressed on the

Is it possible to trigger a specific directive instance's function when a global keyboard shortcut is pressed and it has the class "focused" based on ng-class? Below is some template code: home.html <body ng-controller="SampleController"> ...