Customize the appearance of polygons in OpenLayers 2 by adjusting the fill color and opacity

I am aiming to use different fill colors and opacity values for various shapes (such as Triangle, Circle, Square, Hexagon, etc.).

Although I can draw the shapes, set different titles, and stroke colors with the code below, I'm struggling to define the fill color and opacity values.

I have consulted the documentation, which suggests using "fillColor" and "fillOpacity" properties, but they do not seem to work as expected.

  function GetLonLatObj(lat, lon){
 
        var lonLat = new OpenLayers.LonLat( lon ,lat )
        .transform(
            new OpenLayers.Projection("EPSG:4326"), // Transformation aus dem Koordinatensystem WGS 1984
            map.getProjectionObject() // in das Koordinatensystem 'Spherical Mercator Projection'
        );
        
         return lonLat
    }
  
    var points = []
    var fontColor = "blue";
    var title = "Test";
    
    var map = new OpenLayers.Map("mapdiv");

    map.addLayer(new OpenLayers.Layer.OSM());

    var zoom=16;

    latLonPoint = GetLonLatObj("46.76", "7.606944444444444");
    latLonPoint2 = GetLonLatObj("46.735", "7.543055555555555");
    latLonPoint3 = GetLonLatObj("46.7169444", "7.569166666666667");
    latLonPoint4 = GetLonLatObj("46.76", "7.606944444444444");
        
    latPoint = latLonPoint.lat
    lonPoint = latLonPoint.lon
        
    latPoint2 = latLonPoint2.lat
    lonPoint2 = latLonPoint2.lon
        
    latPoint3 = latLonPoint3.lat
    lonPoint3 = latLonPoint3.lon
        
    latPoint4 = latLonPoint4.lat
    lonPoint4 = latLonPoint4.lon

    //var point = new OpenLayers.Geometry.Point(828260.4259880, 5933577.75538379);
    point = new OpenLayers.Geometry.Point(lonPoint, latPoint);
    point2 = new OpenLayers.Geometry.Point(lonPoint2, latPoint2);
    point3 = new OpenLayers.Geometry.Point(lonPoint3, latPoint3);
    point4 = new OpenLayers.Geometry.Point(lonPoint4, latPoint4);

    points.push(point);
    points.push(point2);
    points.push(point3);
    points.push(point4);
                    
    var selected_polygon_style = {
        
        strokeWidth: "3",
        strokeColor: fontColor,
        fontColor: "red",
        fontSize: "16px",
        fontWeight: "bold",
        fontColor: "black",
        label: title
    };
    
    vectorLayer = new OpenLayers.Layer.Vector();
    
    vectorLayer.style = selected_polygon_style;
    //map.addLayers([vector]);
 
    vectorLayer.addFeatures([new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points))]);
 
    map.addLayers([vectorLayer]);
    
    var markers = new OpenLayers.Layer.Markers( "Markers" );
    map.addLayer(markers);
    
    markers.addMarker(new OpenLayers.Marker(latLonPoint));
    
    map.setCenter (latLonPoint, zoom);
<script src="https://buhli.dyndns.org:444/openlayers.js"></script>

<html>
<body>

  <div id="mapdiv"></div>
  
</body>
</html>

Could anyone offer assistance on how to achieve this?

Thank you very much and best regards

Answer №1

The issue arose from the LineString used in the given command.

vectorLayer.addFeatures([new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points))]);

I was able to resolve it by substituting it with a LinearRing.

A LinearRing is a type of LineString that is closed, unlike a regular LineString which may or may not be closed.

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

Troubleshooting: jQuery ajax form is not functioning as expected

After attempting various methods to create a basic jQuery Ajax form, I am puzzled as to why it is not submitting or displaying any notifications. Below is the code I have been working with: Javascript ... <script type="text/javascript" src="assets/js ...

The second AJAX request isn't functioning properly; it should only be executed once the first one has successfully completed

I am experiencing an issue with my ajax calls. The second call should only be triggered after the first one is successful. However, even though the first call always returns success, I keep getting an error for the second one. function proceedWithUnlock(t ...

Cypress has the ability to exclude certain elements from its testing

How do I locate a clickable element using the cypress tool? The clickable element always contains the text "Login" and is nested inside the container div. The challenge lies in not knowing whether it's an <button>, <a>, or <input type=& ...

Steps for showcasing stars (1-5) based on the data stored in the database

I recently completed a project where I created a user achievement page that displays their progress. Within the page, there is a table containing the user's level. The table structure looks like this: Users( id, username, password, sum_score, level) ...

Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using ...

Creating an attractive image carousel using jQuery or YUI for your website

I am searching for a javascript-based slideshow solution for images. I have received the following requirements: The slideshow should fade one image into another, looping back to the first image after all images have been displayed It must include naviga ...

Add the URL link according to the specific domain name

I am looking for a way to attach additional URL parameters to any links that contain example.com on a webpage. The current script I have only works if the link does not already have parameters attached to it. <script> document.body.innerHTML = d ...

What is the most efficient way to save a document in mongoose based on a specific user's

Is there a way to ensure that when saving a template, it is associated with the user id? I have added a reference to the templateSchema for the User. User.model.js var UserSchema = new mongoose.Schema({ _id: { type: String, required: true, index: {uniq ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

Utilize VBA in Excel to interact with a jQuery button on a web page

Can anyone provide assistance with my VBA Excel code issue? Set ieDoc = Nothing Set ieDoc = ieApp.Document For Each Anchor In ieDoc.getElementsByTagName("div") If InStr(Anchor.outerHTML, "CategoryIDName-popup") > 0 Then ...

Move the footer to the bottom of the page

Is there a way to position my footer at the bottom of the screen and make it extend to the full width in a responsive manner? https://i.sstatic.net/19lSB.jpg Custom CSS for Footer: * { margin: 0; } html, body { height: 100%; } .page-wrap { min-heig ...

Event handling in Node.js can sometimes result in throwing exceptions

I need advice on how to handle errors or return values from an event in my code. Here is what it looks like: _initConnection(){ try{ const errorValidation = this.errorValidation const HOST = "192.168.2.32" ...

Activating events with Jquery

Can anyone help me with this HTML and jQuery issue I'm facing? When I click on an image for the first time (when it has the class 'hide'), the first jQuery click function is executed. However, when I click on the image again, the second func ...

Tips for incorporating fading text and a CTA into your content block

I am looking to protect the full content of my blog posts and allow access only to subscribed members. I want readers to see just a glimpse of the article before it disappears, prompting them to take action with a Call to Action (CTA) like in the fading te ...

Which jquery Grid is capable of handling a constant flow of updates in json format?

Provided below is a brief summary of this extensive post (please read the entire post to provide an answer): Current Implementations: The website retrieves a large json dataset (approximately 30kb, already compressed) The data is rendered as an HTML tab ...

Alter the CSS display based on the user's userAgent if they are using an iPhone and window.navigator.standalone is set to true

Looking to create a unique webAPP with different content displays based on how it is accessed. If the user opens the webAPP through their Safari browser Or if they open the webAPP from a webclip on their home screen The detection is functioning, as conf ...

Inserting data with special characters from an Ajax POST request into a database

I am facing an issue with my form that contains text inputs. When I use an ajax event to send the values via POST to my database PHP script, special characters like ' " \ cause a problem. If the string contains only numbers/letters and no special ...

Guide to making a JavaScript button that triggers an iframe to open upon user clicking the button

I'm currently enhancing the comment section for posts on my website. I am looking to implement a button in javascript that, when clicked, will open an iframe window displaying comments similar to how Facebook does on their post. If there are other lan ...

Inserting a picture using CSS

I attempted to include an image in a footer div, but I have not been successful with the following approach: Here is the HTML code I tried: <footer> <div class="imagenFooter" style="background-image: url(&quot;./images/footer-bg.jpg&quo ...

Create a vertical scrollable feature for the <ul> element when it is set to flex, limiting its height within the specified dimensions

In order to enhance user experience, I have implemented a live search bar that is only visible on mobile screens. For the CSS styling: .search-results { z-index: 9999; width: 80vw; position: absolute; top: 80%; left: 10%; } .search-results li ...