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
    });

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

Enable automatic scrolling when a button on the previous page has been clicked

Imagine there are two buttons (Button 1 and Button 2) on a webpage (Page A). Clicking on either button will take you to the same external page (Page B). How can we ensure that Button 1 takes you to the top of Page B, while Button 2 automatically scrolls do ...

Utilize jQuery to style the background of the webpage, while excluding the Modal element when using Bootstrap

I'm currently working on implementing foggy.js () to create a blurred background effect for Bootstrap's Modal. While I've successfully blurred all elements in the background, the Modal Popup itself is also appearing blurry. So my question is ...

Modifying a Json file in a Node application, while retaining the previously stored data

In my node script, I have a simple process where I update the db.json file via a form. The file is successfully updated, but when I try to render it in response for a GET or POST request, it only shows the previous results. var cors = require('cors&ap ...

Issue with IntersectionObserver not detecting intersection when the root element is specified

I am encountering an issue with my IntersectionObserver that is observing an img. It works perfectly when the root is set to null (viewport). However, as soon as I change the root element to another img, the observer fails to detect the intersection betwee ...

Utilizing ReactStrap: a guide to retrieving the id of the chosen dropDownItem

In my code, I have a dropdownList component with various DropdownItems: <Dropdown isOpen={this.state.dropdownOpen[3]} toggle={() => { this.toggle(3); }} > <DropdownToggle className="my-dropdown" car ...

Monitoring of access controls on Safari during uploads to S3

Safari 10.1.2 Encountering an issue intermittently while attempting to upload PDF files to S3 using a signed request with the Node aws-sdk. Despite working smoothly 90% of the time, have been pulling my hair out trying to resolve this problem. Could it be ...

Injecting resolve into Angular controller and encountering undefined value in logging operation

My setup involves the following: .state('posts', { url: '/posts/{id}', templateUrl: 'posts.html', controller: 'postsController as postsCtrl', resolve: { post: getSinglePostWrapper ...

Effective steps after Ajax request

Whenever a user clicks the "like" button, I perform a check in the database to see if they have already liked the photo. This check is done using ajax. If the photo has already been liked, the success message will indicate "already liked", otherwise it wi ...

Switch between two PHP files with a toggle feature using jQuery click event

Need help with toggling between two PHP files - cab.php and d3.php. Toggling within the same file works fine, but encountering issues when trying to toggle from one file to another. function botaod2mostraesconde() { $(".wrapd2").toggle(); $( ...

Trouble uploading an audio blob as a base64 string using Google Drive API with the drive.files.create method - File ID could not be located

My current challenge involves sending an audio blob to a specific Google Drive folder. To accomplish this, I convert the blob into a file before initiating the transfer process. However, I have encountered an error from the beginning: Error: File not fo ...

iOS devices do not support the add/removeClass function

This code functions properly on desktop browsers, but encounters issues when used on iPhones. Furthermore, the script mentioned below seems to be causing problems specifically on iPhone devices. var $event = ($ua.match(/(iPod|iPhone|iPad)/i)) ? "touchstar ...

Change a nested for-loop into an Observable that has been transformed using RxJS

Currently, the following function is operational, but I consider it a temporary solution as I'm extracting .value from a BehaviorSubject instead of maintaining it as an observable. Existing Code Snippet get ActiveBikeFilters(): any { const upd ...

How can you verify user identity in Firebase when making a call to a cloud function on a

I have integrated Firebase into my React Native app, and I have only enabled anonymous login feature. Currently, I am attempting to invoke a Cloud Function from the app without utilizing the firebase SDK. Instead, I intend to make the call using axios. De ...

Transforming Lapton images into JPEG format on the fly

I have been working on a project where I am compressing jpeg images to .lep format. Now, I have created an .exe file that can convert the .lep image back to jpeg. My goal is to write a simple JSP script that can decode the .lep image on-the-fly and displ ...

Event object not being passed to function in UIWebView Javascript onclick event

When inserting HTML dynamically using simple NSStrings and then loading it into a UIWebview, the following approach is taken: [NSString stringWithFormat:@"<div onclick=\"MyClickEvent(e);\"....some more text here"> A function is defined li ...

Could you provide the parameters for the next() function in Express?

Working with Express.js to build an API has been a game-changer for me. I've learned how to utilize middlewares, handle requests and responses, navigate through different middleware functions... But there's one thing that keeps boggling my mind, ...

Submitting a form and using Ajax to upload an image

Is there a way to submit an image file to php using ajax without assigning the file to a variable with onchange event? I've tried triggering the request on submit click, but keep getting the error message: "cannot read property 0 of undefined." <ht ...

The argument provided needs to be a function, but instead, an object instance was received, not the original argument as expected

I originally had the following code: const util = require('util'); const exec = util.promisify(require('child_process').exec); But then I tried to refactor it like this: import * as exec from 'child_process'; const execPromis ...

Refresh cloned element after making changes to the original element

Just starting to explore Jquery and looking for some guidance to get me started :) Question: I'm facing an issue with a cart total price that is displayed in a different part of the page using clone(). I want this cloned price to automatically update ...

Warning: UnsupportedRepoVersionError: The repository versions are not compatible. Please check the version of IPFS-JS (0.55.3) and Node.js (14.17.0) being used

Recently, I delved into the world of ipfs js and currently have version 0.55.3 installed (https://www.npmjs.com/package/ipfs). Alongside, my setup includes node js version 14.17.0 (LTS) on MacOS BigSur 11.4. However, while following a tutorial at https:// ...