Learn the best way to populate Google Map popup windows with multiple values and include a button to pass unique ID values

I'm facing an issue with my code. When I click on a marker, it should display "Madivala, 12.914494, 77.560381,car,as12" along with a button to pass ID values. Can someone help me figure out how to move forward? http://jsfiddle.net/cLADs/123/

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">

      <script type='text/javascript' src="https://maps.googleapis.com/maps/api/js?key=&v=3.0&sensor=true&language=ee"></script>


  <style type='text/css'>
    #map-canvas {
    width: 500px;
    height: 500px;
}
  </style>




<script type='text/javascript'>//<![CDATA[
window.onload=function(){
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
    content: ''
});

// Our markers
markers1 = [
    ['0', 'Madivala', 12.914494, 77.560381, 'car','as12'],
    ['1', 'Majestic', 12.961229, 77.559281, 'third','as13'],
    ['2', 'Ecity', 12.92489905, 77.56070772, 'car','as14'],
    ['3', 'Jp nagar', 12.91660662, 77.52047465, 'second','as15']
];

/**
 * Function to init 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]);
    }
}

/**
 * Function to add marker to 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];

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

    gmarkers1.push(marker1);

    // Marker click listener
    google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
        return function () {
            console.log('Gmarker 1 gets pushed');
            infowindow.setContent(content);
            infowindow.open(map, marker1);
            map.panTo(this.getPosition());
            map.setZoom(15);
        }
    })(marker1, content));
}

/**
 * Function to filter markers by category
 */

filterMarkers = function (category) {
    for (i = 0; i < markers1.length; i++) {
        marker = gmarkers1[i];
        // If is same category or category not picked
        if (marker.category == category || category.length === 0) {
            marker.setVisible(true);
        }
        // Categories don't match 
        else {
            marker.setVisible(false);
        }
    }
}

// Init map
initialize();
}//]]> 

</script>

</head>
<body>
  <div id="map-canvas"></div>
<select id="type" onchange="filterMarkers(this.value);">
    <option value="">Please select category</option>
    <option value="second">second</option>
    <option value="car">car</option>
    <option value="third">third</option>
</select>

</body>

</html>

Answer №1

This special pen is designed to provide answers to your questions and display the results in the console when requested: http://codepen.io/Saar/pen/OyNeEY?editors=101

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

// List of markers
markers1 = [
    ['0', 'Madivala', 12.914494, 77.560381, 'car','as12'],
    ['1', 'Majestic', 12.961229, 77.559281, 'third','as13'],
    ['2', 'Ecity', 12.92489905, 77.56070772, 'car','as14'],
    ['3', 'Jp nagar', 12.91660662, 77.52047465, 'second','as15']
];

/**
 * Function to initialize 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]);
    }
}

/**
 * Function to add marker to 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);

    // Marker click listener
    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 onclick="getid(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));
}
function getid(id) {
console.log(id)
}
/**
 * Function to filter markers by category
 */

filterMarkers = function (category) {
    for (i = 0; i < markers1.length; i++) {
        marker = gmarkers1[i];
        // If is same category or category not picked
        if (marker.category == category || category.length === 0) {
            marker.setVisible(true);
        }
        // Categories don't match 
        else {
            marker.setVisible(false);
        }
    }
}

// Initialize the map
initialize();

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

What Causes the "Not a String or Buffer Type" Unhandled Exception?

I've encountered an error that seems to be originating from the following line of code, even though I believe I am following the example correctly (viewable at https://www.npmjs.org/package/aws-sign). Any help or hints would be greatly appreciated. v ...

What is the best way to incorporate client and server components in nextJS when params and query parameters are required?

I'm having difficulty understanding the client/server component concept in nextJS 14 (using app router). Below is an example page illustrating how I typically structure it and what components are required: I need to extract the id value from params ...

Struggling with customizing the style of react mui-datatables version 4

Currently, I am utilizing "mui-datatables": "^4.2.2", "@mui/material": "^5.6.1", and have attempted to customize the styling in the following manner: Refer to the Customize Styling official documentation for more details // CUSTOMIZING MUI DATATABLES imp ...

Unavailability of dates in Json ajax DatePicker

After retrieving database records of dates and converting them into a JSON Object, I am attempting to pass the JSON to javascript. The goal is to make the DatePicker UI dynamic by marking the dates in the JSON as unavailable on the calendar. Unfortunately ...

How to implement a for loop within a Vue.js method

Within Vuejs, I have a method that updates multiple variables based on user selection. methods: { updateChart(){ this.chart1.series[1].data = [this.$store.state.selectedcities[0].value[1]]; this.chart1.series[2].data = [this.$store.state.selecte ...

How can I manually transclude content within a directive into two separate locations?

When trying to access the result of ng-repeat, I discovered that using the transclude function and manually compiling could help. However, this method does not work in situations with two places and elements containing ng-repeat. Here is how my code is str ...

AngularJS Uncaught ReferenceError: variable is not

I am facing an issue where I cannot retrieve a value from a function. I am performing REST requests for testing purposes and when trying to get a date, it always returns undefined. An Illustration $http.get('app/components/home/controller/test_calen ...

Retrieving Content within <b></b> Tags from an RSS Feed XML (with Javascript/React)

After parsing an RSS Feed from Upwork, I have extracted job item data points such as title and link. However, a significant amount of the necessary information about each job (category, skills, etc) is buried within the "content" data item as one large blo ...

Step-by-step guide on loading an external javascript file once a webpage is fully loaded, and incorporating a function from it

After the initial page load, I have a need to incorporate an external JavaScript file into an HTML file. This is necessary because a variable in this external JS file only updates after the HTML file has fully loaded. Additionally, I want to utilize the fu ...

Retrieving an array using the $.post() method

I am utilizing the following code: $.post('fromDB.php', function(data) { eval(data); console.log(data); updateTimer(); }); In order to retrieve arrays from PHP. This is what PHP returns: var todayTimeMinutes = [0, 45, 35, 25, 40, 0 ...

Submitting JSON data using JavaScript

My goal is to send a username and password to my backend server. However, I am encountering an issue where the data does not successfully reach the backend when using the following code: function register() { var text = '{"username":"admin1","pass ...

What is the best way to merge various scope models in Angular?

I am currently working with the following variables: $scope.formTitle = ''; $scope.formDesc = ''; $scope.fields = []; However, I would like to merge these into a single object named $scope.theForm for easier conversion to ...

A guide to updating a button in Angular:

Currently, I have implemented a directive that displays 3 tabs at the bottom. However, I am curious to know if it is possible to swap out "exterior" for "interior" based on whether I am on the exterior or interior page. For example, when on the exterior ...

Tips on transferring information from a component to an instance in Vue

My goal is to retrieve data from a component and transfer it to a variable within my root Vue instance. Vue Instance Configuration: new Vue({ el: '#root', data: { searchResultObject: '' }, methods: { // ...

Generate pre-set components using fundamental building blocks

Can I predefine some props for components? In my Vuetify example, let's say I want to customize the v-btn component with specific props. This custom implementation would act as a child component while still providing all the functionalities of the par ...

Discovering the smallest and largest values in an object literal using JavaScript

I am looking to extract the minimum value from an object literal and utilize it in AngularJS, as shown below: scope.data = { 'studentName' : "Anand", 'socialStudies' : "98", 'english' : "90", 'math' ...

Caution: The `className` property does not align with Material UI css which may cause issues upon reload

https://i.stack.imgur.com/MxAiY.png If you are facing the error/missing CSS, check out this video for a visual representation. While older versions of similar questions exist on Stack Overflow such as React + Material-UI - Warning: Prop className did not ...

dart, setting the root directory for web application

I'm looking to include some sample websites in my web framework package. Currently, the sites work fine when running them as Dart-only implementations, but if I need to compile them to JavaScript, I have to manually move the subfolder from my package& ...

Transferring information between an ASP web form page and an Angular2 application

Currently, I am working on a project that involves dealing with a legacy WebForms system. The system is gradually being updated to Angular 2, but the transition is happening incrementally. In order to effectively integrate information from the legacy sect ...

What is the best way to continuously compare two date variables every minute using Javascript?

In my script, I have two date variables - one representing the current time and the other two minutes later. My goal is to compare both values every minute and trigger a function when the current time is greater than or equal to the latter time. Unfortun ...