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:

https://i.sstatic.net/OxG4t.png

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)

https://i.sstatic.net/Hcsjb.png

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

How about connecting functions in JavaScript?

I'm looking to create a custom function that will add an item to my localStorage object. For example: alert(localStorage.getItem('names').addItem('Bill').getItem('names')); The initial method is getItem, which retrieves ...

Troubleshooting Firebase functions that end with socket hang up error ECONNRESET

For the past two years, my Firebase Function has been successfully retrieving data from an external service with soap, parsing it, and sending it back to an Android app client. However, recently it suddenly stopped working without any changes on my part, g ...

What could be causing the issue of not being able to access an element visible in AngularJS Videogular?

I am currently working on integrating the videogular-subtitle-plugin with the most recent version of Videogular/AngularJS. As a newcomer to AngularJS, I believe there must be a simple solution that I am overlooking. My main challenge lies within a directi ...

Unexpected object returned by the spread operator

Currently, I am utilizing node and specifically using babel-node. "start": "nodemon --exec babel-node --presets es2015 index.js" However, I have encountered an issue with my spread syntax in the following code snippet: export const login = async (parent ...

Pausing and then resuming an interval function within the same function

I'm struggling with an $interval function that runs every second. The function retrieves user credentials from local storage and checks if they have expired. If they have, it refreshes them with new ones. Otherwise, it does nothing. This is what my ...

Displaying and hiding the top menu when the div is scrolled

I have developed a script that is designed to display the menu in a shaking motion and hide it as you scroll down. It functions properly when scrolling within the body of the webpage, but I am facing issues when attempting to do so with a div that has an o ...

Display the input value in AngularJS in a customized format without changing the format in the model

When receiving an integer indicating a duration in minutes, I want to display it as hours or days if it exceeds a certain value. The ng-model should still keep the value in minutes so that any user changes are reflected accurately. For example: Reading & ...

How can Swiper efficiently display the next set of x slides?

After exploring SwiperJS at https://swiperjs.com/, I've been unable to locate an option that allows the slide to return immediately to the right once it goes out of view on the left. The current behavior poses a problem where there is no next slide o ...

Passing and removing array parameters in HTTP requests using Angular

I have an Array of statuses objects. Each status has a name and a boolean set to false by default. These represent checkboxes in a form with filters - when a checkbox is checked, the boolean value is set to true: const filters.statuses = [ { name ...

The replace() function is failing to replace the provided inputs

Supposedly, when a user types in certain profanity and submits it, the word is supposed to be replaced with a censored version. Unfortunately, this feature is not working as expected. The word appears uncensored. Do you think implementing if/else stateme ...

"Exploring the process of integrating a controller into an external HTML file using AngularJS

I'm relatively new to AngularJS. In my web app, I have a set of buttons: index.html <button class="aButton">a</button> <button class="bButton">b</button> <script> $(document).ready(function(){ $(".aButton"). ...

Perform a MongoDB find() query using the _id field as the search criteria

So I am currently working on my express app and I need to find data based on the _id field in MongoDB. Below is a snippet of my MongoDB record: { "_id": { "$oid": "58c2a5bdf36d281631b3714a" }, "title": "EntertheBadJah" ...

Invoke a controller in Prestashop by utilizing AJAX technology

I am struggling to figure out how to call the method / function in my controller. The controller is named TestController.php, and I also have files named Test.tpl and Test.js. Additionally, I am unsure of what to put in the URL field. My goal is to retrie ...

Ensure that the control button is pressed during the JavaScript onclick event function

I am looking to create a JavaScript function that checks if the CTRL button is pressed. Here is my PHP code: <tr class="clickable" onclick="gotolink('<?= base_url() . invoices/createinvoice/' . $customer->Id; ?>')"> And here ...

Instructions for selecting a checkbox using boolean values

According to the HTML specification, you should use the checked attribute in the <input type="checkbox"> tag to indicate that it is checked. However, I only have a boolean value of either true or false. Unfortunately, I am unable to manipulate the b ...

Unable to run for loop in vue.js

Hello, I'm a newcomer to using Vue.js and am encountering an issue with executing a simple for loop in my code. Any assistance or guidance would be greatly appreciated. Here is the snippet of my code: var Vue = require('vue'); Vue.use(requi ...

Exploring the contrast between 'completed' and 'upcoming' in callback functions within node.js

Within the passport documentation for authentication configuration, there is a function that appears rather intimidating as it utilizes the enigmatic function "done." passport.use(new LocalStrategy( function(username, password, done) { User.findOne( ...

SignOut operation in Express.js Firebase instantly responds with a status of 200 to the client-side Fetch POST request

I'm currently facing an issue with my POST request setup using the Fetch API in my client-side JavaScript. The request is being sent to my server-side JavaScript code which utilizes Express Js and Firebase Auth. The problem arises when the auth().sign ...

Creating multiple routes within a single component in Angular without triggering unnecessary redraws

Within the ChildComponent, there is a reactive form that allows for data entry. Upon saving the filled form, the route should be updated by appending an id to the current route. Currently, when saving, the component renders twice and causes screen flicke ...

Utilize various CSS styles for text wrapping

I'm struggling to figure out where to begin with this problem. My goal is to create a three-column row that can wrap below each other if they cannot fit horizontally. The height of the row should adjust to accommodate the items while maintaining a fix ...