What is the process for displaying distinct icons for Google Map markers?

In my project, I am trying to display different marker icons on Google Maps. Below is the code snippet that I have used for this purpose. The markers array contains various types of markers with custom icons that I want to show on the map. You can view the implementation in this JSFiddle link: https://jsfiddle.net/h9seLt22/7/. Instead of using the default marker icon, I need to dynamically display these custom marker icons.

angular.module('myApp', [])
    .controller('MapCtrl', [
    '$scope', '$http', '$compile',

function ($scope, $http, $compile) {
    //-------------------------------------------------------------------------------------------------------------------------------------------------
    $scope.find = function () {

        var gmarkers1 = [];
        var markers1 = [];
        var infowindow = new google.maps.InfoWindow({
            content: ''
        });

        // Our marker data
        markers1 = [
            ['0', 'Madivala', 12.914494, 77.560381, 'computer science,electronic system,communication thoery,english', 'as12', 'Abi Tech ACC','http://static4.wikia.nocookie.net/__cb20131121214007/destinypedia/images/7/71/Information_Icon.svg'],
            ['1', 'Majestic', 12.961229, 77.559281, 'electronic system,Telecommunication,optical&fiber optics', 'as13', 'Vell Infotech','http://icons.iconarchive.com/icons/kyo-tux/aeon/256/Sign-LogOff-icon.png'],
            ['2', 'Ecity', 12.92489905, 77.56070772, 'communication thoery,english,Digital Electronics,signal&systems', 'as14', 'vinoth coching center','http://icons.iconarchive.com/icons/artua/mac/512/Intranet-icon.png'],
            ['3', 'Jp nagar', 12.91660662, 77.52047465, 'Digital Electronics,signal&systems', 'as15', 'Gpy tech archi','http://www.psdgraphics.com/file/upload-icon.jpg']
        ];

        /**
         * Initialize the map
         */

        function initialize() {
            var center = new google.maps.LatLng(12.9667, 77.5667);
            var mapOptions = {
                zoom: 12,
                center: center,
                mapTypeId: google.maps.MapTypeId.TERRAIN
            };

            map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
            for (i = 0; i < markers1.length; i++) {
                addMarker(markers1[i]);
            }
        }

        /**
         * Add markers to the map
         */

        function addMarker(marker) {
            var category = marker[4];
            var title = marker[1];
            var pos = new google.maps.LatLng(marker[2], marker[3]);
            var content = marker[1];
            var fullContent = marker.slice(1, 6).join();

            var marker1 = new google.maps.Marker({
                title: title,
                position: pos,
                category: category,
                map: map
            });

            gmarkers1.push(marker1);

            // Click listener for markers
            google.maps.event.addListener(marker1, 'click', (function (marker1, idx, markers1) {
                return function () {
                    console.log('Gmarker 1 gets pushed');
                    var compiled = '<div><div>' + markers1[idx][0] + ' </div><div>' + markers1[idx][1] + ' </div><div>' + markers1[idx][2] + ' </div><div><button id="' + markers1[idx][5] + '">Get</button></div></div>';
                    var infowindow = new google.maps.InfoWindow({
                        content: compiled
                    });
                    infowindow.open(map, marker1);
                    map.panTo(this.getPosition());
                    map.setZoom(15);
                }
            })(marker1, i, markers1));
        }

        $(document.body).on('click', 'button', function () {
            console.log(this.id);
        });

        /**
         * Filter markers based on category
         */

        filterMarkers = function (category) {
            for (i = 0; i < markers1.length; i++) {
                marker = gmarkers1[i];
                if (marker.category.toLowerCase().indexOf(category.toLowerCase()) > -1 || category.length === 0) {
                    marker.setVisible(true);
                } else {
                    marker.setVisible(false);
                }
            }
        }

        // Initialize the map
        initialize();

    }
}]);
#map-canvas {
        width: 500px;
        height: 500px;
    }
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="MapCtrl" ng-init="find()">
        <div id="map-canvas"></div>
        <select id="type" onchange="filterMarkers(this.value);">
            <option value="">Please select category</option>
            <option value="computer science">computer science</option>
            <option value="electronic system">electronic system</option>
            <option value="communication thoery">communication thoery</option>
            <option value="english">english</option>
            <option value="optical&fiber optics">optical&fiber optics</option>
            <option value="Digital Electronics">Digital Electronics</option>
            <option value="signal&systems">signal&systems</option>
        </select>
    </div>
    </div

Answer №1

To set a specific icon for a marker, you can use the Marker object initializer:

var marker = new google.maps.Marker({
            title: location[1],
            position: new google.maps.LatLng(location[2], location[3]),
            category: location[4],
            map: $scope.map,
            //icon: location[7] //set icon
        });

Alternatively, you can set the icon using the google.maps.Marker.setIcon function:

 var imageIcon = {
            url: location[7],
            size: new google.maps.Size(32, 32),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(0, 32)
        };
        marker.setIcon(imageIcon);

Below is an updated example that illustrates how to customize marker icons:

Updated Example

angular.module('myApp', [])
    .controller('MapCtrl', [
    '$scope', '$http', '$compile',

function ($scope, $http, $compile) {


    $scope.filterMarkers = function () {
        var category = $scope.selectedItem;
        for (var i = 0; i < $scope.markers.length; i++) {
            var marker = $scope.markers[i];
            if (marker.category.toLowerCase().indexOf(category.toLowerCase()) > -1 || category.length === 0) {
                marker.setVisible(true);
            } else {
                marker.setVisible(false);
            }
        }
    };

    //-------------------------------------------------------------------------------------------------------------------------------------------------
    $scope.initMap = function () {

        $scope.markers = [];
        var infowindow = new google.maps.InfoWindow({
            content: ''
        });

       
        var locations = [
            ['0', 'Madivala', 12.914494, 77.560381, 'computer science,electronic system,communication thoery,english', 'as12', 'Abi Tech ACC', 'http://icons.iconarchive.com/icons/martz90/hex/32/location-icon.png'],
            ['1', 'Majestic', 12.961229, 77.559281, 'electronic system,Telecommunication,optical&fiber optics', 'as13', 'Vell Infotech', 'http://icons.iconarchive.com/icons/graphicloads/100-flat/32/location-icon.png'],
            ['2', 'Ecity', 12.92489905, 77.56070772, 'communication thoery,english,Digital Electronics,signal&systems', 'as14', 'vinoth coching center', 'http://icons.iconarchive.com/icons/graphicloads/seo-services/32/location-icon.png'],
            ['3', 'Jp nagar', 12.91660662, 77.52047465, 'Digital Electronics,signal&systems', 'as15', 'Gpy tech archi', 'http://icons.iconarchive.com/icons/graphicloads/transport/32/location-icon.png']
        ];

        
        function initialize() {
            var center = new google.maps.LatLng(12.9667, 77.5667);
            var mapOptions = {
                zoom: 12,
                center: center,
                mapTypeId: google.maps.MapTypeId.TERRAIN
            };

            $scope.map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
            for (var i = 0; i < locations.length; i++) {
                addMarker(locations[i]);
            }
        }

        
        function addMarker(location) {

            var marker = new google.maps.Marker({
                title: location[1],
                position: new google.maps.LatLng(location[2], location[3]),
                category: location[4],
                map: $scope.map,
                //icon: location[7] //set icon
            });


            var imageIcon = {
                url: location[7],
                size: new google.maps.Size(32, 32),
            };
            marker.setIcon(imageIcon);

            $scope.markers.push(marker);

            
            google.maps.event.addListener(marker, 'click', (function(){
                var compiled = '<div><div>' + location[0] + ' </div><div>' + location[1] + ' </div><div>' + location[2] + ' </div><div><button id="' + location[5] + '">Get</button></div></div>';
                var infowindow = new google.maps.InfoWindow({
                        content: compiled
                });
                infowindow.open($scope.map, marker);
                $scope.map.panTo(this.getPosition());
                $scope.map.setZoom(15);
            }));
        }
       

        initialize();

    }
}]);
#map-canvas {
  width: 500px;
  height: 500px;
}
 <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
 <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
 <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>
 <div ng-app="myApp">
        <div ng-controller="MapCtrl" ng-init="initMap()">
            <div id="map-canvas"></div>
            <select id="type" ng-model="selectedItem" ng-change="filterMarkers()" >
                <option value="">Please select category</option>
                <option value="computer science">computer science</option>
                <option value="electronic system">electronic system</option>
                <option value="communication thoery">communication thoery</option>
                <option value="english">english</option>
                <option value="optical&fiber optics">optical&fiber optics</option>
                <option value="Digital Electronics">Digital Electronics</option>
                <option value="signal&systems">signal&systems</option>
            </select>
        </div>
    </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

No value found for the existing property

Recently, I began working on building a RESTful API using node.js, express, and mongodb. The progress was smooth until now, where I encountered a problem with the authentication route for users: apiRoutes.post('/authenticate', function(req, res) ...

What methods can be utilized to enhance the visual appeal of a threejs model

I'm currently working on enhancing the visual quality of my 3D models, aiming for smoother edges and more realistic shadows. To achieve this, I am experimenting with an OBJ file format. Here's the code snippet I'm using to load and display t ...

Tips for transferring information from ng-view to the navbar on the index.html page using AngularJS

Recently, I embarked on a journey to learn the MEAN stack and decided to challenge myself by building an authentication page from scratch instead of using the out-of-the-box solution. My main struggle lies in updating texts on my navbar. Here's a snip ...

How to transfer the value of a prop from a function to the render method in React.JS

After successfully making a get request from my React App to the backend and receiving the values, I am facing an issue with setting the value to the front end DOM. Here is a snippet of how my current class looks: class App extends React.Component{ co ...

What is the best way to retrieve a response from a PHP file as an array through Ajax?

Seeking assistance in retrieving a complete address by entering the postal code in an HTML form textbox and clicking a button. The setup involves two files - one containing the ajax function and the other housing the PHP code. Uncertainty looms over whethe ...

What is the best way to store various types of functions within a single object key?

I have a dilemma where I am storing values and individual typed functions in an array of objects. Whenever I loop through the array, all the types of all typed functions in the array are required for any value. How can I make this more specific? Check it ...

JS, Express: Encounter issues - unable to find view in directory despite following provided instructions

Currently, I am following the steps outlined in this guide: Despite conducting extensive research, I am facing difficulty in getting it to work as expected. Here is the folder structure I am working with: https://i.sstatic.net/jCEdO.png Below is a snipp ...

Is there a method to instruct crawlers to overlook specific sections of a document?

I understand that there are various methods to control the access of crawlers/spiders to documents such as robots.txt, meta tags, link attributes, etc. However, in my particular case, I am looking to exclude only a specific portion of a document. This por ...

I wish to trigger the function when the button with the ID "add_city" is clicked instead of it being activated upon pressing the Enter key as it currently is

Is it possible to trigger the function by clicking a button with the id "add_city", rather than just pressing Enter? function createCity(stateId, newCity, event) { if(event.keyCode == 13 || $(this).attr('id') === 'add_city') { i ...

Adjusting CSS to switch up the color scheme

Is there a way to allow users to change the background color of pull quotes by using the input type="color tag within a form element? Below is my current HTML structure: <form action="change.php" method="post"> name: <input type="text"> ...

What steps do you take to establish a relay connection for pagination in an ORM framework?

After thorough research of Relay's documentation, I have yet to find a clear explanation on how to establish a Relay connection with an ORM. The examples provided mainly utilize the connectionFromArray method, which works well for data stored in memor ...

What is the best way to implement a prev.next function in an image gallery using an array in JavaScript?

In the image gallery, you can simply click on each image to view a larger version. The enlarged image sources are pulled from the background-image of the smaller images. What I am aiming to achieve is the addition of previous and next buttons for easy navi ...

Unleashing the power of JavaScript: A guide to dynamically generating nested arrays

Can you take a look at the code below and help me find the mistake? function pair(str) { // Function to pair specific letters in a string for (var i = 0; i < str.length; i++) { // Check and pair letters based on certain conditions if (s ...

React developer server is failing to automatically refresh the code

I've encountered an issue with react-dev-server where changes I make to the code do not reflect on the app itself even after refreshing (not hot-loading). I've tried setting up my own project as well as using Facebook's Create-react-app, whi ...

The server is showing a discrepancy in date comparisons with MomentJS

I am struggling with grouping events by day in my application. While it works correctly in the development environment (Brazil), on the server (USA) the events that occur at the end of the day are being placed at the beginning of the next day. I suspect th ...

The functionality of cropping is not supported within a Bootstrap modal

I have been using ngimgcrop successfully to crop images within my application. However, I encountered an issue when trying to display the cropped images inside a uibmodal (AngularJS modal). Despite trying various solutions, such as using ng-init, I was una ...

Retrieve progress with easing using jQuery's animate() function

At the moment, I'm utilizing this code to create an animation for a bar-graph-inspired element: $('.anim').animate({ right: `${100-(e/max*100)}%`, backgroundColor: colors[0] },{ duration: 1500, easing: 'easeInQuart&apos ...

Generate a fresh array containing two columns extracted from the original array

In my current coding project, I am working with an array structured like this: elements = [ {"year": 2010, "month": 11, "day":23} {"year": 2009, "month": 10, "day":15} {"year": 2009, "month": 10, "day":10} //added after my edit below ] The task at hand i ...

What is the best method for comparing two JSON objects in AngularJS?

I am working with two JSON objects. $scope.car1={"Sedan":{"Audi":["A4","A3"]},"Hatchback":{"Maruthi":["Swift"]}}; $scope.car2={"Hatchback":{"Maruthi":["Swift"]},"Sedan":{"Audi":["A3","A4"]}}; I have attempted to compare these two objects using the co ...

Click on the button to reveal the hidden content within the div, and then smoothly scroll down to view

I have a footer div that is present at the bottom of every page on our site. I've added a button to expand this div, but I'm looking for a way to automatically scroll the page down so that the user can view the expanded content without manually s ...