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

Guide to using jQuery to input a multi-line text into a field

Dealing with a value that spans multiple lines obtained from PHP has been challenging due to the structure of textareas. The standard method of inserting it into the textarea is not feasible in this case. I resorted to using jQuery for this purpose, but ...

Leverage JavaScript to retrieve the formatting of an element from an external CSS stylesheet

Check out this HTML snippet: <html> <head> <link rel="stylesheet" type="text/css" media="all" href="style.css"> </head> <body> <div id="test">Testing</div> <script> ...

The dropdown menu in AngularJS is unable to retrieve the selected index

Presently, I have a dropdown menu: <select class="form-control" name="timeSlot" ng-model="user.dateTimeSlot" ng-change="dateTimeChanged(user.dateTimeSlot)" ng-blur="blur29=true" required style="float: none; margin: 0 auto;"> ...

Ways to modify the jquery script to display on page load rather than on scrolling action

Currently in the process of working on my site, www.runebs.dk. Utilizing a script to activate information for each project. JS.. $('.showHide').on('click',function(){ $(this).toggleClass('active'); $( '#subHead ...

The issue of Ajax response not triggering the ng-click function

When attempting to pass data through an AJAX return, I encountered an issue with a function that writes an ng-click in Angular 1. The code snippet is as follows: $.ajax({ 'method': 'GET', 'url': base_url +&apos ...

Having difficulty integrating plugins like Lighthouse into my Cypress project

I need assistance with integrating the cypress automation plugin into my project. I made changes to my index.js file in the plugin folder, but now I am receiving this error: cy.lighthouse() is not a function Here is my index.js file content: const { light ...

"Transferring an array of data to a Laravel controller via AJAX: A step-by-step guide

Is there a way to send arrays of data to the back-end all at once? The Problem 1. This is what I'm currently sending: array:5 [ "_token" => "S5s5ZTTnnP93MyXgCql0l9vhHsiqt5VWaFyEedXj" "product_id" => "21" "specification_id" => "6" " ...

What is the best way to choose all <pre> tags that have just one line of content?

$('pre:contains("\n")') will target all <pre> elements that have one or more newlines. Is there a way to specifically select <pre> tags with no newline or only one at the end? Any shortcuts available? match <pre>A< ...

When clearInterval is used to stop a setInterval, it will not automatically restart if reset with setInterval

I am facing an issue with a countdown timer that I have created using setInterval in JavaScript. The timer is supposed to countdown from one minute at one second intervals. However, when I click the "start" button, it starts the countdown but if I click an ...

Having Trouble Changing CSS with Rails Link_to CSS ID

While following the ruby on rails guide, I came across a specific way to write link_to's with a css id: <%= link_to "About", about_path, id: "third" %> I also attempted: <%= link_to ("About", :id => "third"), about_path %> Although ...

ES6 Generators: lack of informative stack trace when using iterator.throw(err)

The ES6 approach: iterator.throw(err) is often explained as inserting an exception as if it happened at the yield statement within the generator. The challenge lies in the fact that the stack trace of this exception does not include any information about t ...

The table's width exceeds the appropriate size

Take a look at the code snippet below <%-- Document : index Created on : Feb 7, 2014, 1:03:15 PM --%> <%@page import="java.util.Map"%> <%@page import="java.util.Iterator"%> <%@page import="analyzer.DataHolder"%> <%@p ...

My onClick AngularJS function contains a for loop that is not functioning properly upon initial click

When I click on a student's name in my AngularJS app, the program is supposed to show the student's full name and list of tuitions. However, I am encountering an issue where the for loop does not work on the first click, but it works fine on the ...

Tips for incorporating animation while altering element styles within JavaScript

I am looking to incorporate a sliding animation that moves the element downward when the display property is set to block, and upward when it's set to none or an empty string, here is the current JavaScript code I have: <script> function showQ ...

The HTML password input continues to respond to key bindings, even when other inputs are not affected by the bindings

In the ongoing development of a legacy react application, I encountered keybindings that are causing unexpected behavior. For instance, pressing the "F" key triggers the full screen mode within the app. However, this keybinding is inadvertently active for ...

What is the process of defining a route for a JSON response in an Express application?

I've been following an Angular tutorial on handling form submissions with promises, which I found here. My server is running on Node and I'm using Express to manage routes. However, when I submit the form and reach the line var $promise = $http. ...

Passing data from a method callback to a function and returning a variable in the same function

Is there a way to properly return the latlon variable from the codeAddress function? The typical 'return latlon' doesn't seem to work, possibly due to scope issues. Any suggestions on how to resolve this? function codeAddress(addr) { ...

Is there a way to align my two tables next to each other using CSS?

.page { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 20px; } .items { float: left; } .secondItem { vertical-align: text-top; float: right; } .page-header table, th, td { border: 1px solid; display: block; background-color: ...

Uncovering the array within Javascript

I'm struggling to figure out why I can't access an array that PHP sends back to me. When AJAX makes a call, I send back this: $response['success'] = true; In my PHP file, I use echo json_encode($response); to send it. However, when I ...

Responsive HTML grid with a distinct line separating each row

My challenge is to create a layout that features a grid of floating divs with horizontal lines under intermediate rows. The catch is that there should not be a line under the last row, and if there is only one row of elements, no line should be displayed. ...