Tips for resizing the background to match the font size on a canvas marker in Google Maps

Check out my jsFiddle code below:

 var marker = new google.maps.Marker({
              position: new google.maps.LatLng(-25.363882,131.044922),
              map: map,
              title:"Hello World!",
              icon: CanvasCrear("hola", 15)
          });

I'm attempting to style the marker similar to this example:

function CanvasCrear(texto, height_)  {

    var canvas = document.createElement("canvas");
    var context;
    var txtWidth; 

    txtWidth = canvas.getContext("2d");   
    txtWidth.font = "12px Sans-Serif";

    var width_ =  txtWidth.measureText(texto).width;
    
    canvas.setAttribute("width", (width_ + "px"));
    canvas.setAttribute("height", (height_ +"px"));

    context = canvas.getContext("2d");   
    context.font = "12px Sans-Serif";

    context.fillStyle = "black";
    context.fillText(texto, 0, 12);

    document.body.appendChild(canvas);
}

window.onload = function() {
    var texto = " " + "hola mundo" + " ";
    var height = 15;
    CanvasCrear(texto, height);
};

I have limited experience with canvas manipulation and would appreciate any suggestions or tips on how to improve this. Thank you!

Answer №1

If you're looking to enhance your map, consider integrating your canvas into a CustomMarker

Take a look at this proof of concept fiddle

  function CustomMarker(latlng,  map, text) {
    this.latlng_ = latlng;
    this.text_ = text;
    // Once the LatLng and text are set, add the overlay to the map.  This will
    // trigger a call to panes_changed which should in turn call draw.
    this.setMap(map);
  }

  CustomMarker.prototype = new google.maps.OverlayView();

  CustomMarker.prototype.draw = function() {
    var me = this;

    // Check if the div has been created.
    var div = this.div_;
    if (!div) {
      // Create a overlay text DIV
      div = this.div_ = document.createElement('DIV');
      // Create the DIV representing our CustomMarker
      div.style.border = "none";
      div.style.position = "absolute";
      div.style.paddingLeft = "0px";
      div.style.cursor = 'pointer';


        CanvasCrear(this.text_, 15,div)

      google.maps.event.addDomListener(div, "click", function(event) {
        google.maps.event.trigger(me, "click");
      });

      // Then add the overlay to the DOM
      var panes = this.getPanes();
      panes.overlayImage.appendChild(div);
    }

    // Position the overlay 
    var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
    if (point) {
      div.style.left = point.x + 'px';
      div.style.top = point.y + 'px';
    }
  };

  CustomMarker.prototype.remove = function() {
    // Check if the overlay was on the map and needs to be removed.
    if (this.div_) {
      this.div_.parentNode.removeChild(this.div_);
      this.div_ = null;
    }
  };

  CustomMarker.prototype.getPosition = function() {
   return this.latlng_;
  };

code snippet:

function CanvasCrear(texto, height_, div) {
  var context;
  var canvas = document.createElement("canvas");
  canvas.style.cssText = 'color: Black; background: #ffffff; background: url(data:image/svg+xml; base64, PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwJS...

// Tell me more about it...
var lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus efficitur quam semper felis condimentum, non placerat urna vulputate. Quisque nec mauris metus.";

console.log(lorem);
 html {
   width: 100%;
   height: 100%;
 }
 body {
   width: 100%;
   height: 100%;
   margin: 0;
 }
 #map_canvas {
   width: 100%;
   height: 100%;
 }
<script src="http://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map_canvas" width="300" height="200"></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

What is the most effective method for creating a dark background with light text in Bootstrap without using SASS?

I recently created a new website using Bootstrap 5 and set the background color to black (#000000) by adding some CSS styling. However, I noticed that this change had unintended consequences on the appearance of various elements such as drop shadows, modal ...

Displaying a specific division solely on mobile devices with jQuery

I need to implement a feature where clicking on a phone number div triggers a call. However, I only want this div to be displayed on mobile devices. To achieve this, I initially set the div to "display:none" and tried using jQuery to show it on mobile devi ...

A Comprehensive Guide to Handling Errors in Angular 4: Passing the err Object from Service to Component

Currently, I am in the process of developing a login page using Angular for the front-end and Spring Security for the back-end. Everything appears to be functioning correctly, except for handling exceptions when attempting to catch errors from the service ...

Can you identify this numerical category?

Can you identify this number type? console.log(0100); // output 64 console.log(050); // output 40 console.log(010); // output 8 In a hexadecimal system, it would be: 0100 = 256 050 = 80 010 = 16 ...

Determine the starting position of a div's CSS bottom using jQuery before the hover animation begins

Currently, I am in search of the CSS value 'bottom' for each div that belongs to the 'shelf-info-text' class. These particular divs can be found inside a parent div called 'shelf-item'. The bottom value is determined automati ...

What is the best way to use appendChild within an AJAX get function to manipulate the DOM

I've been working on a code function where I try to append a list item (li) into the HTML received in 'msg', but it's not functioning properly. Any ideas why? function handleFileSelect(evt) { var files = evt.target.files; $(&ap ...

Unable to pinpoint the source of the excess spacing within a form field

There appears to be some extra space in the text field of my form, extending beyond the container margin. Please refer to the image and JSFiddle http://jsfiddle.net/GRFX4/. Any thoughts on what might be causing this issue? Thank you. HTML: <div id="co ...

What steps can I take to safeguard my Javascript from unauthorized access by external entities?

Basically, I have a website with a Javascript library that has ads integrated through a script tag. My main concern is whether these ads can access my Javascript library, which makes Ajax calls to a server where the user is logged in. I want to protect my ...

Break down and simplify the code into individual components

<input type='button' class="myButton" onclick="document.body.style.cssText+=';background-image: url(img01.jpg);background-repeat: no-repeat; -moz-background-size: cover; -o-background-size: cover; background-size: cover;';" value="S ...

Encountering issues with SignInWithRedirect feature's functionality

Whenever I attempt to SignInWithRedirect in my React project, I am redirected to a Google site where I only see a blue progress bar at the top before quickly being redirected back to my website. My intention is to be shown my Google sign-in options, but it ...

What is the best method to retrieve duplicate fields from a database in HTML5?

this.db.transaction(function (tx) { tx.executeSql('SELECT tsk.*, cont.firstName, cont.lastName ,cont1.firstName, cont1.lastName, list.listId FROM tbl_tasks tsk, tbl_contacts cont,tbl_contactequests cont1, tbl_lists list WHE ...

AngularJS File Input element triggering only once when selecting the same file

I have created an Angular directive to customize the file upload input. directive('ngFile', function () { return { link: function (scope, element, attrs) { var button = element.find('button[data-fileInputButton]&apos ...

Having difficulty positioning content inside a div element

I am working with a set of three divs, each containing a .header class and a .content class. While I have managed to align the .header class correctly, I am facing an issue with aligning the .content class below the header with 10-15px padding on all sides ...

Is it possible to render array items into separate divs using the .map() method without displaying commas?

After extensive searching, I have only come across solutions that involve using .join() to combine the items into a single string. const createCard = () => { const pokemonTypes = ['grass', 'fire', 'water']; return ...

Navigating through images within my application

When setting images, I encounter an issue where the second image overlaps the first one instead of appearing separately. How can I ensure that each image is displayed in its own box? I have attempted to use a blob directly by returning imgUrl in the showI ...

I need a counter in my React application that is triggered only once when the page scrolls to a specific element

I've encountered a challenge with a scroll-triggered counter on a specific part of the page. I'm seeking a solution using React or pure JavaScript, as opposed to jQuery. Although I initially implemented it with states and React hooks, I've ...

Move the JavaScript code from the <script> element in the HTML file to a

Recently, I've been exploring the idea of incorporating a tradingview ticker on my website. Trading view has kindly provided me with a snippet to embed into my webpage: <!-- TradingView Widget BEGIN --> <div class="tradingview-widget-co ...

Replace all instances of the same word with the word "and" using regular expressions

If we look at the sentence below: Blue shirt blue hat Can regular expressions be used to detect 2 matching words and replace the second one with and so it reads: Blue shirt and hat Now, let's tackle a more complex example. In this case, we nee ...

What is the best way to add data from an array to a DOM element in the same order it was retrieved from Firebase?

Utilizing Google Firebase Firestore for data storage and the Open Movie Database (OMD) in combination with Axios to retrieve movie information. I am currently developing a website that allows users to add movies to collections. On the collections page, al ...

Conundrum encountered: SIGTRAP causing Electron failure to initialize

Exploring Electron for creating desktop applications has been my recent endeavor. However, I encountered this pesky error: /home/me/dev/my-electron-app-2/node_modules/electron/dist/electron exited with signal SIGTRAP Since the path leads to a binary file, ...