Using multiple unique markers on Google Maps

Currently trying to grasp the concept of creating a customized Google map. I have limited experience with javascript but I'm eager to learn.

I found some code online that helped me understand how to add locations, markers, and infowindows, but now I am struggling to figure out how to incorporate multiple custom icons for each marker.

Your assistance would be greatly appreciated.

function initialize() {

        //add map, specify type
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 6,
            center: new google.maps.LatLng(37.7749295, -122.4194155),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        //define locations
        var locations = [
            ['San Francisco: Power Outage', 37.7749295, -122.4194155],
            ['Sausalito', 37.8590937, -122.4852507],
            ['Sacramento', 38.5815719, -121.4943996],
            ['Soledad', 36.424687, -121.3263187],
            ['Shingletown', 40.4923784, -121.8891586]
        ];

        //initialize marker as 'i'
        var marker, i;

        //declare infowindow
        var infowindow = new google.maps.InfoWindow();

        //add marker to each location
        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                map: map,
            });

            //click event on marker, shows infowindow
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    infowindow.setContent(locations[i][0]);
                    infowindow.open(map, marker);
                }
            })(marker, i));
        }
    }
    google.maps.event.addDomListener(window, 'load', initialize);

Answer №1

If you want to customize the appearance of markers in Google Maps, one simple method is to specify an icon URL for each marker.

Here's a sample code snippet:

// Updated array with custom icon URLs
var locations = [
            ['San Francisco: Power Outage', 37.7749295, -122.4194155,'http://labs.google.com/ridefinder/images/mm_20_purple.png'],
            ['Sausalito', 37.8590937, -122.4852507,'http://labs.google.com/ridefinder/images/mm_20_red.png'],
            ['Sacramento', 38.5815719, -121.4943996,'http://labs.google.com/ridefinder/images/mm_20_green.png'],
            ['Soledad', 36.424687, -121.3263187,'http://labs.google.com/ridefinder/images/mm_20_blue.png'],
            ['Shingletown', 40.4923784, -121.8891586,'http://labs.google.com/ridefinder/images/mm_20_yellow.png']
        ];

// Inside a loop
marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                map: map,
                icon: locations[i][3]
            });

Answer №2

    let districts = [
        ['San Francisco: Major Outage', 37.7749295, -122.4194155],
        ['Sausalito', 37.8590937, -122.4852507],
        ['Sacramento', 38.5815719, -121.4943996],
        ['Soledad', 36.424687, -121.3263187],
        ['Shingletown', 40.4923784, -121.8891586]
    ];

The array 'districts' contains names of various locations along with their latitude and longitude coordinates which are used to pinpoint them on Google Maps. These coordinates can be fetched from a database or JSON file. I hope this clarification is helpful.

Answer №3

    <div id="location-map"></div>

  <script type="text/javascript">          
     function initializeMap() {
         //display map with specified options
           var mapOptions = {
               zoom: 5,
               draggable: true,
               animation: google.maps.Animation.DROP,
               mapTypeId: google.maps.MapTypeId.ROADMAP,
               center: new google.maps.LatLng(51.4964302,-0.1331412), // designated location
               styles:[{"stylers":[{"saturation":-100},{"gamma":1}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"poi.business","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"poi.business","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"poi.place_of_worship","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"poi.place_of_worship","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"geometry","stylers":[{"visibility":"simplified"}]},{"featureType":"water","stylers":[{"visibility":"on"},{"saturation":50},{"gamma":0},{"hue":"#50a5d1"}]},{"featureType":"administrative.neighborhood","elementType":"labels.text.fill","stylers":[{"color":"#333333"}]},{"featureType":"road.local","elementType":"labels.text","stylers":[{"weight":0.5},{"color":"#333333"}]},{"featureType":"transit.station","elementType":"labels.icon","stylers":[{"gamma":1},{"saturation":50}]}]
           };
           var mapElement = document.getElementById('location-map');
           var map = new google.maps.Map(mapElement, mapOptions);

         //add multiple locations
             var locations = [
                 ['London office', 51.4964302,-0.1331412,'http://labs.google.com/ridefinder/images/mm_20_red.png'],
                 ['Sausalito', 37.8590937, -122.4852507,'http://labs.google.com/ridefinder/images/mm_20_red.png'],
                 ['Sacramento', 38.5815719, -121.4943996,'http://labs.google.com/ridefinder/images/mm_20_green.png'],
                 ['Soledad', 36.424687, -121.3263187,'http://labs.google.com/ridefinder/images/mm_20_blue.png'],
                 ['Shingletown', 40.4923784, -121.8891586,'http://labs.google.com/ridefinder/images/mm_20_yellow.png']
             ];
             //create marker for each location
             var marker, i;
             //initialize infowindow
             var infowindow = new google.maps.InfoWindow();
             //add marker to each location on the map
             for (i = 0; i < locations.length; i++) {
                 marker = new google.maps.Marker({
                     position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                     map: map,
                     icon: locations[i][3]
             });
             //click event for markers, open infowindow
             google.maps.event.addListener(marker, 'click', (function(marker, i) {
                 return function() {
                     infowindow.setContent(locations[i][0]);
                     infowindow.open(map, marker);
                 }
             })(marker, i));
         }
     }
     google.maps.event.addDomListener(window, 'load', initializeMap);
  </script>

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

loading JSON file using dynamic JavaScript techniques

My Raspberry Pi is running a C++ application in the background that performs complex mathematical calculations based on sensor input and generates results every second. I want to showcase this data on a website by having the application create a JSON file ...

How to Import JSON Files into JavaScript

My goal is to retrieve information from a local JSON file to use in my JavaScript file. I attempted to do this by loading the file and assigning its contents to variables, but I am encountering difficulties. Here's the code snippet I have been working ...

What is causing my app to crash with this particular line of code?

I've noticed several similar questions on this site and tried adjusting my code accordingly, but it still doesn't resolve the issue. My app loads with buttons, one of which opens a class file displaying a map on the screen. Here is the code for ...

The onClick action kicks in as soon as the page finishes loading

One particular line of code in the Button Tag has caught my attention. let content = this.props.searchResult.map((ele, i) => { let card_id = ele.user.username + "_card"; return( <div className="col s12 m6 l4" key={i} id={card_id}> ...

To modify the text within the pagination select box in ANTD, follow these steps:

Is it possible to modify the text within the ant design pagination select component? I have not been able to find a solution in the documentation. I specifically want to replace the word "page" with another term: https://i.sstatic.net/w55hf.png ...

Is it possible to configure Express.js to serve after being Webpacked?

I am currently in the process of setting up a system to transpile my Node server (specifically Express) similar to how I handle my client-side scripts, using webpack. The setup for the Express server is quite straightforward. I bring in some node_modules ...

Warning: Unhandled promise rejection occurred while running the test

Currently delving into the world of selenium with a focus on testing the registration page. I've crafted a registration page class equipped with methods for monitoring registrations. However, upon attempting to execute a test within the application cl ...

What is the best way to utilize the GET Method with a hashtag incorporated into the URL?

For instance: www.sample.com#?id=10 Currently, I am not able to retrieve any value from $_GET['id']. Despite my attempt to eliminate the hashtag from the URL using JavaScript, no change occurs: $(document).ready(function(){ $(window.location ...

transmitting comfort through events

To enhance my application, I am working on publishing a solace message to a topic and then passing it along to another part of the app for further processing using events. This entire process is happening within a single node.js process. While I understand ...

The concept of "Object Reference Pattern" in the world

Currently, I am working with a single object: var callback = { onValueChange: function () { }, onTabPressed: function () { }, onFocus: function () { } }; In my webpage, I have various editors such as textEditor and numericEditor, and I bind t ...

retrieve information from a URL's OpenGraph metadata

Does anyone know of any comprehensive tutorials that demonstrate how to retrieve opengraph data from a URL using JavaScript, similar to the functionality seen on Facebook when pasting a link into a post or on Yahoo Mail when inserting a URL into an email? ...

Angular tutorial: Organizing data by date only

This is my first time building an Angular app. I am fetching JSON data from an API using a factory service to get football match fixtures. My goal is to group these fixtures by date while disregarding the time component. The date string in the JSON is fo ...

Form validation on the client side: A way to halt form submission

I have a form with several textboxes. The unobtrusive jquery validation is functioning properly and correctly turns the boxes red when invalid values are entered. However, I've noticed that when I click to submit the form, it gets posted back to the s ...

Steps for creating a basic prioritized event listener system in JavaScript

I am currently working on an event/listener manager that has the following function: var addListener = function(event, listener) { myListeners[event].push(listener); //assume this code works } However, I now need to modify it so that it appears a ...

Unable to access object key data from JSON-SERVER

I am currently attempting to send a GET request to json-server in order to retrieve data from a nested object. However, the response I am receiving is empty instead of containing the desired data key. After thoroughly reviewing the documentation, I could ...

Save array data to a file in Node.js once it finishes looping

I've been struggling to find a solution to my issue despite looking at examples from other questions. I have created a basic web scraper in nodejs that stores data in an array and now I need help writing this data to a file. I'm having difficulty ...

Utilizing identical ID values multiple times to link to the identical location

I am currently working on a horizontal grid project with 3 image squares. My goal is to create an action where clicking on any grid section will anchor the user down to a slideshow box displayed below the grid. Below is an example of one grid section and ...

show fixed div when in view

After seeking inspiration from this specific thread on SO, I still need some help. The challenge I'm facing involves displaying a sticky footer within a parent div that is positioned halfway down the page. I've tried multiple tutorials, but none ...

What is the best method to change the value of a nearby TD text box?

I am currently developing a shopping cart application that requires me to update product screens based on users' previous orders stored as local JSON data. The product screen is built using JSON returned from the server. My goal now is to automatical ...

Assigning a Value to a Dropdown Menu in Angular

I have some JSON data that contains a True/False value. Depending on whether it is true or false, I want a specific option in a Select Dropdown to be automatically selected. This is the HTML code using Angular 16: <select name="reportNo" id=& ...