Customizing Marker Images in Google Maps JavaScript API

Currently, I am using a workaround to rotate a custom image marker in Google Maps.

The issue I am encountering is regarding sizing. For example, if my PNG image is 400px wide and 200px high.

When rotating the image so the width becomes vertical, it gets cut off.

I am unsure how to fit the image within the bounds. Initially, I thought of pseudo code like this but couldn't make it work:

const image = currentImage;
if(image.width > image.height){
   //make bounding box of marker image.width squared 
} else{
   //make bounding box of marker image.height squared
}

For reference, here is my rotation function:

function rotate() {
const images = $("#map").find("img").get();
  for (let i = 0; i < images.length; i++) {
      if ($(images[i]).attr("src").replaceAll(window.location.origin, "") === currentMarker.itemSrc) {
         $(images[i]).css({
             'transform': 'rotate(' + currentDeg + 'deg)',
         });
         break;
    }
  }
}

This is how I add a marker: (ignore the custom fields I added)

    const markerIcon = {
        url: currentImage.src + "#" + allMarkers.length,
        // size: new google.maps.Size(?, ?),
        // origin: new google.maps.Point(?, ?),
        // anchor: new google.maps.Point(?, ?)
    };

    const marker = new google.maps.Marker({
        position: mapsMouseEvent.latLng,
        map: map,
        draggable: true,
        icon: markerIcon,
        itemSrc: currentImage.src.replaceAll(window.location.origin, "") + "#" + allMarkers.length,
        id: lat + "," + lng,
        optimized: false
    });

https://i.sstatic.net/MObLD.png

https://i.sstatic.net/nHPQQ.png

Answer №1

After searching extensively, I have finally discovered a resolution. The following code snippet will enlarge your marker DIV container and align the image in the center.

No need to concern yourself with the custom field rotation. This field is not applicable for the custom image marker. It was introduced solely for monitoring and updating the image’s rotation.

const selectedImage = whateverYourImageIs;

    let markerSize;
    let origin;
    if(selectedImage.naturalWidth > selectedImage.naturalHeight){
        markerSize = selectedImage.naturalWidth;
        origin = new google.maps.Point(0 , -(markerSize - selectedImage.naturalHeight) / 2);
    } else {
        markerSize = selectedImage.naturalHeight;
        origin = new google.maps.Point(-(markerSize - selectedImage.naturalWidth) / 2 , 0);
    }




function createMarker(position, iconImage, label, rotation, markerSize, origin) {

const markerIcon = {
    url: iconImage,
    labelOrigin: new google.maps.Point(20, 20),
    size: new google.maps.Size(markerSize, markerSize),
    origin: origin,
    anchor: new google.maps.Point(0,0)
};

return new google.maps.Marker({
    position: position,
    map: map,
    draggable: true,
    icon: markerIcon,
    optimized: false,
    label: label,
    rotation: rotation
});
}

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

Accessing data in vuex can result in Firebase SnapShot.val() returning null

I am developing an application that allows access for students, staff, and non-teaching staff. Here is how my form data is structured: formData: { name: "", email: "", password: "", select: null }, options: ["Student", "St ...

What is the best way to send an inline SVG string to my controller?

I am trying to send an inline svg string along with some other properties to my controller. When I replace the svg string with a normal string like "blabla", it successfully reaches my controller. However, with the actual svg string, it never makes it to ...

Formatting HTTP HTML response in Vue.js can be achieved by utilizing various methods and techniques

I have a WordPress site and I'm trying to fetch a specific post by its ID. Currently, the content is being displayed successfully, but it's also showing HTML tags in the main output. Here is an example: https://i.stack.imgur.com/f3pdq.png Code ...

Guide to using JavaScript to populate the dropdown list in ASP

On my aspx page, I have an ASP list box that I need to manually populate using external JavaScript. How can I access the list box in JavaScript without using jQuery? I am adding the JavaScript to the aspx page dynamically and not using any include or impor ...

React-Native-SVG encountered an error: Invariant Violation - the component "RNSVGGroup" could not be found in the UIManager

Trying to create an SVG in React-Native using react-native-svg. I have set up a React-Native-CLI. After doing some research, I attempted to solve the issue on my own and found something useful. I tried running cd ios && pod install. I wasn't ...

What is the best way to convert API data into a currency format?

Hello, I need assistance with formatting data retrieved from an API into a currency format. The code below successfully retrieves the data but lacks formatting. For instance, if the data displays as 100000000, I would like it to be formatted as IDR100.000. ...

Once the PHP page loads, it becomes challenging for me to dynamically change values in JavaScript

Within my code snippet below, I am aiming to modify the initial value using a slider. The slider appears to be functioning correctly; however, it is not updating the values of timeout as indicated beneath the line $('ul.<?php echo $this->session ...

Updating a MongoDB subarray with $set now includes adding a new entry rather than just updating existing ones

When trying to update an object in a sub-array, instead of replacing and updating the data, it adds a new entry. Here is the code from controller.js: const updateSubCategory = asyncHandler(async (req, res) => { const { dataArray } = req.body ...

What is the process of converting PUG to JSX?

I am currently attempting to integrate Pug code within a JS react application. While researching, I came across this plugin here, which can assist in converting the code. However, it seems to have an issue with handling the "." statements present in the c ...

Why is the result of this specific JavaScript code a string?

let x = 2, y = x = typeof y; console.log(x); // >> 'string' Could you explain why the value of x ends up being a string in this code snippet? ...

What is the best way to animate various sprites using distinct buttons in HTML and CSS?

I've been experimenting with animating a sprite by using different onClick button triggers. I encountered an issue where only one of the buttons works correctly in the fiddle. However, in my local file version, the other buttons work but only once and ...

The "Splash Screen Div" page displayed during transitions and page loading

Creating a "Splash Screen Div" for a loading page involves waiting until everything is loaded and then hiding or moving the div off screen. Below is an example: index.html <div id="loading-Div"> <div id="bear-Logo"> < ...

Steps for integrating a valid SSL certificate into a Reactjs application

After completing my ReactJS app for my website, I am now ready to launch it in production mode. The only hurdle I face is getting it to work under https mode. This app was developed using create-react-app in a local environment and has since been deployed ...

Retrieving PHP output from multiple arrays using AJAX

I'm new to AJAX and I'm struggling to retrieve arrays. My goal is to update a notification bar in real time using AJAX. I've managed to update the count displayed on the balloon, but I can't figure out how to also fetch messages from My ...

Consistently obtaining the same outcome in JavaScript, always

Is it possible to resolve this issue? I keep getting a result of less than 18 when trying numbers 1-100, even though the output should be for values under 18. In my HTML code, there is a <p> element with id="result", an input with id=&quo ...

Dealing with AJAX errors in React components after mounting

Facebook suggests that the optimal method for loading initial data in a React component is to execute an AJAX request within the componentDidMount function: https://facebook.github.io/react/tips/initial-ajax.html It would look something like this: ...

What is the best way to retrieve information utilizing Http.get within my project?

I have a TypeScript file containing user data: File path: quickstart-muster/app/mock/user.mock.ts import {User} from "../user"; export const USERS:User[]=[ new User(....); ]; I have a service set up at: quickstart-muster/app/services/user.service.ts ...

I encountered an error while attempting to import a file into Firebase Storage

I've been struggling to upload files from Firebase Storage and encountering errors despite reading the documentation and various blogs on the topic. I'm looking for the most effective approach to resolve this issue. import { storage } from ' ...

Black screen issue with JW Player on iPad

I am currently using the JW Player to embed my videos and facing an issue with them not playing on iPads or iPhones. It seems like a problem with the HTML5 video tag as the screen remains black when trying to play the videos. Below is the code snippet for ...

Create a global variable by importing an external module in TypeScript

I am currently developing a TypeScript npm module called https://www.npmjs.com/package/html2commonmark. This module is versatile and can be utilized in nodejs (via require) as well as in the browser (by loading node_modules/html2commonmark/dist/client/bund ...