Google Maps API - Custom Label for Map Markers

I am trying to implement a custom map on my website, and everything seems to be working fine except for one issue.

The red marker on the map needs to have a label, but I don't want to use an additional image as an icon. Is there a way to add a label without any extra plugins?

If that doesn't work, is it possible to add the 'mapoptions' to the standard embed map? The only problem with this approach is that it zooms in when scrolling.


Current appearance of the map:


Desired label for the Marker:

Brandenburger Gate - Google Maps


HTML:

<div id="googleMap"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

Javascript (jQuery):

$(function() {

    function showMap() {

        var mapZoom = 14;
        var LatLng = new google.maps.LatLng(52.516275, 13.377704);

        var mapOptions = {
            zoom: mapZoom,
            center: LatLng,
            streetViewControl: false,
            scrollwheel: false,
            navigationControl: false,
            mapTypeControl: false,
            scaleControl: false,
            keyboardShortcuts: false

        };

        var map = new google.maps.Map(document.getElementById('googleMap'),mapOptions);

        var marker = new google.maps.Marker({
            position: LatLng,
            map: map,
            draggable: false
        });
    }
    google.maps.event.addDomListener(window, 'load', showMap);

});

Answer №1

Though this question is old, I experienced the same issue and discovered that using the className property can help attach a class to the label. For more information, click here.

Here's an example:

marker = new google.maps.Marker({
      position: new google.maps.LatLng(lat, lng),
      label: {
            text: "Hello World",
            color: "#203334",
            fontWeight: "bold",
            fontSize: "16px",
            className: "map-label"
      }
});

Answer №2

Give this code a try:

<style type="text/css>
   .labels {
     color: white;
     background-color: red;
     font-family: "Lucida Grande", "Arial", sans-serif;
     font-size: 10px;
     text-align: center;
     width: 10px;     
     white-space: nowrap;
   }
 </style>

 var latLng = new google.maps.LatLng(49.47805, -123.84716);
 var homeLatLng = new google.maps.LatLng(49.47805, -123.84716);

 var map = new google.maps.Map(document.getElementById('map_canvas'), {
   zoom: 12,
   center: latLng,
   mapTypeId: google.maps.MapTypeId.ROADMAP
 });

 var marker = new MarkerWithLabel({
   position: homeLatLng,
   map: map,
   labelContent: "BrandenBurger Tor",
   labelAnchor: new google.maps.Point(22, 0),
   labelClass: "labels" // the CSS class for the label
 });

To enhance the markers with more custom features, check out this resource.

I hope this solution is helpful!

Answer №3

To design a unique marker, start by creating the desired image on a canvas and then utilize the SetIcon function with DataURL as the parameter to implement it.

// Here's a method to generate a custom GoogleMap marker incorporating text 

enter code here

var marker = new google.maps.Marker({position: new google.maps.LatLng(35.1,32), title: "My Custom Marker" }); 

var canvas=document.createElement("canvas"); 
var context = canvas.getContext("2d"); 
canvas.width=50; 
canvas.height=50; 
context.fillText("Hello World!",10,10); 

marker.setIcon(canvas.toDataURL('image/jpeg')); '

Answer №4

One way to utilize the label of google marker is by following this format:

new google.maps.Marker({
                position:latlng,
                map:map,
                label: 'A'
            });

Answer №5

To incorporate the InfoBox third party library and link its position to the marker, consider using the following code snippet:

var labelText = "Brandenburger Tor";

var myOptions = {
  content: labelText,
  boxStyle: {
    border: "none",
    textAlign: "center",
    fontSize: "12pt",
    fontWeight: "bold",
    width: "150px",
    color: "#C70E20"

  },
  disableAutoPan: true,
  pixelOffset: new google.maps.Size(10, -10),
  position: LatLng,
  closeBoxURL: "",
  isHidden: false,
  pane: "mapPane",
  enableEventPropagation: true
};

var ibLabel = new InfoBox(myOptions);
ibLabel.open(map);
var marker = new google.maps.Marker({
  position: LatLng,
  map: map,
  draggable: false
});
marker.bindTo('map', ibLabel);
marker.bindTo('position', ibLabel);

Check out a proof of concept fiddle here

https://i.stack.imgur.com/bYRAj.png

Snippet of the Code:

$(function() {

  function showMap() {

    var mapZoom = 14;
    var LatLng = new google.maps.LatLng(52.516275, 13.377704);

    var mapOptions = {
      zoom: mapZoom,
      center: LatLng,
      streetViewControl: false,
      scrollwheel: false,
      navigationControl: false,
      mapTypeControl: false,
      scaleControl: false,
      keyboardShortcuts: false
    };

    var map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);

    var labelText = "Brandenburger Tor";

    var myOptions = {
      content: labelText,
      boxStyle: {
        border: "none",
        textAlign: "center",
        fontSize: "12pt",
        fontWeight: "bold",
        width: "150px",
        color: "#C70E20"
      },
      disableAutoPan: true,
      pixelOffset: new google.maps.Size(10, -10),
      position: LatLng,
      closeBoxURL: "",
      isHidden: false,
      pane: "mapPane",
      enableEventPropagation: true
    };

    var ibLabel = new InfoBox(myOptions);
    ibLabel.open(map);
    var marker = new google.maps.Marker({
      position: LatLng,
      map: map,
      draggable: false
    });
    marker.bindTo('map', ibLabel);
    marker.bindTo('position', ibLabel);
  }
  google.maps.event.addDomListener(window, 'load', showMap);
});
html,
body,
#googleMap {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/infobox/src/infobox.js"></script>
<div id="googleMap"></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

Extract information from page 1 to page 2 by utilizing ajax

Greetings, I am currently facing an issue with parsing data using the href get method to retrieve PHP by ajax on another page. Is this achievable? By the way, my framework of choice is CODEIGNITER. This is my HTML href code snippet: <a href="'.b ...

Send your information to a JSONP endpoint

Can data be posted to JsonP instead of passing it in the querystring as a GET request? I have a large amount of data that needs to be sent to a cross-domain service, and sending it via the querystring is not feasible due to its size. What other alternati ...

There was a glitch encountered while constructing (Verifying type validity) with Prisma

There was an issue in the node_modules/@prisma/client/runtime/library.d.ts file on line 1161, specifically error TS1005 where a '?' was expected. 1161 | select: infer S extends object; | ^ 1162 | } & R ...

What could be causing my page to suddenly disappear?

After saving my changes in the IDE and refreshing the browser to test the prompt() function in my index.js file, the entire page goes blank, showing only a white screen. I double-checked the syntax of my function and it seems correct. Everything else on th ...

arrow function implemented in a React hook for handling onClick event

From my understanding, placing an arrow function in the JSX creates a new reference of a new function each time it is triggered. For example: <p onClick={() => handleClick() /> In older versions of React with classes, we could do this: <p onCl ...

An issue has occurred: The necessary parameter (Slug) was not included as a string in the getStaticPaths function for the /post/[Slug] route

Hello, I've recently embarked on a tutorial journey to create the ultimate Modern Blog App using React, GraphQL, NextJS, and Tailwind CSS. However, I encountered an error that's giving me some trouble specifically when trying to access a post. He ...

Combining various array values into a single key in JSON格式

Issue: I am working on a sign-up form for new users using HTML. The goal is to store multiple arrays (each containing "username: username, password: password, topScore: 0) within one JSON key ("user" key). However, the current functionality only allows f ...

What is the most efficient way to retrieve key pair values of separate elements in an array with just one API request?

The API I am working with returns an array of elements, each containing multiple key-value pairs. An example of a similar API response can be seen here: , where an array of poems is returned. [ { "title": "...." "content": "..." "url" : "..." } ...

Instructions for appending an id to the URL of events in fullcalendar using Rails

Looking for a way to attach an ID to the URL of a fullcalendar event in a Rails application? I am using a json.jbuilder file: json.array!(@estudiante.clases) do |clase| json.extract! clase, :id json.id clase.id json.title clase.name json.start cl ...

Utilizing Angular 5 routerLink for linking to absolute paths with hash symbols

I am facing an issue with a URL that needs to be opened in a new tab. Unfortunately, Angular generates this URL without the # symbol. Currently, we have implemented the following: <!-- HTML --> <a title="Edit" [routerLink] = "['/object/objec ...

Creating a new dynamic page can be achieved by clicking on a dynamically generated link. Would you like to learn how to do that?

Recently, I developed a custom API using Node.js to retrieve information about blogs from Medium.com. The API currently provides: The author/main picture of the article Title A link to the article on medium.com (redundant) The entire article text in the ...

Show the response obtained after making a POST request

In my current project, I am utilizing vanilla JavaScript to send a POST request to my Flask App. I have implemented a validation feature that checks for duplicate usernames when a user is signing up. If the username already exists, a 406 status response is ...

What are the steps to clipping a canvas using CSS clip-path?

When it comes to clipping a canvas, there are multiple methods that can be used. One way is to create a path with getContext('2d') and set globalCompositeOperation. Another method involves using -webkit-clip-path or clip-path, though the latter m ...

Having trouble deleting a Repeatable Job from the Bull queue in Node.js

Upon attempting to utilize the removeRepeatableByKey method, I encountered an error stating that removeRepeatableByKey is not a function. Specifically, it mentioned that queue_1.taskQueue.removeRepeatableByKey is not a function. Furthermore, I am facing d ...

Experience some issues with the NextJS beta app router where the GET request fails when using fetch, but surprisingly works

Having an issue with a GET request while using NextJS with the APP dir... The function to getProjects from /project route.ts is not triggering properly. console.log("in GET /projects") is never triggered, resulting in an unexpected end of JSON ...

Display the item request form whenever a selection of an unidentified item is made using select2

I want to implement select2 for a company search feature. In case the desired company is not available in the existing dataset, I need to provide an option for users to request adding the company data. This is the HTML code: <head> <link href=& ...

Transferring PHP and JavaScript variables via AJAX to PHP page and storing in MySQL database table

After searching through numerous similar questions, I still haven't found the exact answer I need. I have a set of js variables that are sent via ajax to a location.php file, where they will be inserted into a mysql table. The current ajax call looks ...

Having trouble choosing elements with angular.element within ng-repeat loop

In my HTML code, I am using an ngRepeat element: <ol id="animationFrame"> <li ng-repeat="animationImage in animationImages" ng-repeat-listener> <img ng-src="{{animationImage.src}}" id="{{animationImage.id}}"> </li> </ol& ...

Utilizing Jquery UI in Visual Studio 2012 for developing asp.net webforms applications

Recently upgraded to 2012 and encountering some difficulties with implementing a jQuery UI accordion in my default.aspx page. Here is the code snippet from my default.aspx page: <div id="accordian"> <div> <div> ...

Display XML elements on hover with a Bootstrap tooltip

I am attempting to showcase an XML snippet in my title attribute, similar to the example below. I understand that removing data-html="true" or changing it to false will resolve the issue. However, I also require a label in my title resembling the <stro ...