Tips for adjusting the dimensions of a map within the app.component.html

Within the code snippet below, my aim is to adjust the width and height of the map using the style tag shown here:

<style>
     #map3 .map {
        width: 100%;
        height:90px;
      }

</style>

Despite trying various values for width and height, the map's dimensions remain unchanged. Can someone provide guidance on how to successfully modify the width and height of the map?

app.component.html:

<div class="MousePosition">
  <div id="mouse-position"></div>
</div>
<form>
  <label for="projection">Projection </label>
  <select id="projection">
    <option value="EPSG:4326">EPSG:4326</option>
    <option value="EPSG:3857">EPSG:3857</option>
  </select>
  <label for="precision">Precision</label>
  <input id="precision" type="number" min="0" max="12" value="4"/>
</form>
    <div id="map"></div>
    <style>
     #map3 .map {
        width: 100%;
        height:90px;
      }

    </style>
 

app.component.ts:

    ngOnInit() {
    var mousePositionControl = new MousePosition({
      className: 'custom-mouse-position',
      coordinateFormat: createStringXY(7),
      projection: 'EPSG:4326',
      /*render: function(){
        console.log(createStringXY(7));
      },*/
      // To place the mouse position within the map, comment out the following two lines.
      target: document.getElementById('mouse-position'),
      undefinedHTML: '',//for what to be rendered when the mouse leaves map scope: values https://openlayers.org/en/latest/apidoc/module-ol_control_MousePosition-MousePosition.html
    });
  
    this. map = new Map({
      controls: defaultControls().extend([mousePositionControl]),
    target: 'map3',
    layers: [
      new TileLayer({
        source: new XYZSource({
          url: 'http://tile.stamen.com/terrain/{z}/{x}/{y}.jpg'
        })
      })
    ],
    view: new View({
      center: [0, 0],
      zoom: 2
    })
  });

  var projectionSelect = document.getElementById('projection');
    projectionSelect.addEventListener('change', function (event) {
      mousePositionControl.setProjection((event.target as HTMLSelectElement).value);
    });

    var precisionInput = document.getElementById('precision');
    precisionInput.addEventListener('change', function (event) {
    var format = createStringXY((event.target as HTMLInputElement).valueAsNumber);
    mousePositionControl.setCoordinateFormat(format);
    console.log(createStringXY(format));
  });
  
  this.map.on('dblclick', function(evt){
    // Get the pointer coordinate
    //let coordinate = transform(evt.coordinate);
    var lonlat = transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326')
    console.log(lonlat);
  });

  var zoomslider = new ZoomSlider();
  this.map.addControl(zoomslider);
 }

Answer №1

Let's dive into this issue here. When using an open layers map, it draws on a canvas, which cannot be resized using css after rendering. Therefore, the solution is to resize programmatically within your component class.

To achieve this, we can utilize the ngAfterViewInit function to make sure we have a reference to the rendered map before proceeding with resizing:

//...
ngAfterViewInit() {
  this.map.updateSize();
}
//...

This approach should work smoothly, and it applies similarly to other map APIs as well. Since the canvas renders before any other html, it may appear distorted until all components are loaded. Thus, it's crucial to resize it once everything else in your app has been loaded.

For instance:

  • map.component.html
<div id="map"></div>
  • map.component.ts
@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnInit, AfterViewInit {
  // Define a reference to the map
  map: any | undefined;

  ngOnInit() {
    this.map = new Map({
      target: 'map',
      view: new View({
        center: [0, 0],
        zoom: 2
      })
    });
  }

  ngAfterViewInit() {
    this.map?.updateSize();
  }
  
  // Additional functionality can be added below
  
}

For further details, you can refer to this Stack Exchange thread:

I hope this explanation helps!

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

Having trouble preventing the scroll from moving even after setting body overflow to hidden in Next Js

I'm encountering an issue with my Nextjs project where I can't seem to prevent the page from scrolling even after using document.body.style.overflow set to hidden. Here is the code snippet: Code Sandbox Link Upon examining the code: In lines 11 ...

Express.js experienced a 404 error when processing POST requests

When working with js and express, the route handler file looks like this: var express = require('express'); var passport = require('passport'); var authRoutes = App.route('authRoutes'); va ...

Ways to mandate a field to only be of type object in TypeScript

I need to design a type that includes one mandatory property and allows for any additional properties. For instance, I require all objects to have an _id property of type string. {_id: "123"} // This will meet the criteria {a: 1} // This will not work as i ...

What is the best way to combine a QR code and an existing image using Java script?

Looking for help in embedding a created QR code into an existing image. I am proficient in nodeJS, JavaScript, and jQuery. Any assistance would be greatly appreciated. ...

HTML dynamic voting system

I'm new to coding in HTML and I have a specific challenge that I need help with. I want to display a value on my webpage that increases every time a user clicks a button. Below is the code I have written so far: <script type="text/javascript& ...

Encountering a problem when trying to reference socket.io

I've been working on building an express app with chat functionality, but I've run into an issue with socket.io. It's not working properly and is throwing an "uncaught reference" error when I try to run the server. You can see a screenshot o ...

Break up the JavaScript code into modules to avoid duplicating blocks of code detected by

There is a block of code that SONAR has identified as duplicate. I am looking for guidance on how to address this issue. import fields from '../../utils/utils'; dispatch( fields.change([ { id: 'userData', value: ...

Return a string to the client from an express post route

I'm attempting to return a dynamically generated string back to the client from an Express post route. Within the backend, I've set up a post route: router.post('/', async (req, res) => { try { // Here, I perform computations on ...

Is the latest Swiper JS version compatible with outdated web browsers?

Seeking information on browser compatibility. I am interested in upgrading to the latest version 8.4.5 of Swiper JS for my project, currently using version 4.1.6. Upon examining their shared Github repository file .browserslistrc, I noticed changes that ta ...

What is the best way to apply a mask to a textbox to format the date as MM/yyyy using a mask

In my asp.net application, I have a TextBox for entering Credit card date (month & year only). I tried using the 'TextBox with masked edit extender' and set Mask="99/9999" with Mask Type="Date. However, it is not working as expected - it only wor ...

Eliminating redundant values from a JSON object that is nested within another

Currently, I am working on rendering a list of Labels from a local JSON file. However, I am facing the issue of duplicates and I want each label to appear only once. I attempted to use Array.filter() and other methods to achieve this line: "Categories": ob ...

After a postback in JavaScript, the Root Path variable becomes null

I have been attempting to save the Root URL in a JavaScript variable within my _Layout.cshtml like this: <script type="text/javascript> var rootpath = ""; $(document).ready(function () { rootpath = "@VirtualPathUtility.ToAbsolute("~/ ...

Verify that each field in the form contains a distinct value

I have a formarray with nested formgroups. How do I ensure that the elements within each formgroup are unique? Here is an example of my form setup: form: FormGroup = this.formBuilder.group({ fields: this.formBuilder.array([]), }); private createField() ...

Instant Pay Now Option for Your WordPress Website with PayFast Integration

I have encountered an interesting challenge that I would like some guidance on. My goal is to integrate a PayFast "Pay Now" button into a Wordpress.com blog, specifically within a sidebar text widget. The tricky part is that I need the customer to input th ...

Why do my posts appear twice on the page after submitting a new post? When I refresh the page, the posts seem to duplicate

After submitting the create post controller via POST, the post appears once. However, upon reloading the page using GET, it shows up twice. How can I prevent this duplication and ensure that existing posts are only displayed once? I aim to have the post d ...

In React, the issue arises when a Typescript declaration merging cause is referenced as a value but is being mistakenly used as a type

I am trying to come up with a solution to avoid the hassle of brainstorming names that seamlessly incorporate suffixes or prefixes in order to differentiate between declarations and component names. After being inspired by this resource Avoid duplicate id ...

Display endless data within a set window size

I am looking to create a fixed-size window for displaying text from the component <Message/>. If the text is longer, I want it to be scrollable within the fixed window size. See screenshot below: Screenshot export default function AllMessages(){ ...

Load Order Possibly Disrupted by Arrival of Barrel Imports

When attempting to unit test my component, I keep encountering errors related to my import statements: Error: Cannot resolve all parameters for 'MyComponent'(undefined, FormBuilder). TypeError: Cannot read property 'toString' of undef ...

Press one button to activate another button

I am looking to activate a button's class by clicking on another button. The button I have is: <button class="clear-cart banner-btn">clear cart</button> This button is used for clearing a cart. On the order confirmation page, I click on ...

vue mapGetters not fetching data synchronously

Utilizing vuex for state management in my application, I am implementing one-way binding with my form. <script> import { mapGetters } from 'vuex' import store from 'vuex-store' import DataWidget from '../../../../uiCo ...