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 is the best way to extract parameters from a JSON object?

Here is the complete code: $.post('test.php', { id: id },function (data) { console.log(data); var Server = data.response.server; var Photo = data.response.photo; console.log(Server); console.log(Photo); }); When I receive data I get JSON data ...

The functionality of ZoneAwarePromise has been modified within the Meteor framework

After updating to the latest Angular 2.0.1 release on Meteor 1.4.1.1, I'm facing an error that says: Zone.js has detected that ZoneAwarePromise (window|global).Promise has been overwritten I've attempted running meteor update and meteor reset, b ...

Interfacing Highcharts with Angular for seamless data binding across series

I am fairly new to using highcharts and I am having difficulty binding my data into the series parameter. In my controller, I have an array of objects that I want to display (when I use console.log, I can see that they are all properly there) this.plotDa ...

Sort the data - a selection menu is included in each row of the table

My issue involves a datatable where each row must have a select item with multiple options to choose from. The goal is to filter the rows based on the selected option when using the default search bar located above the table. However, I've encountered ...

Highlight the navigation transition in the menu

Is there a more updated tutorial available for creating an underline effect that slides from one link to another when hovered over and remains at the clicked link? I have come across a tutorial on Underline transition in menu which seems to be based on th ...

Error Handling in Angular2 MVC 4 Project Route Issues

Here is the structure of my Mvc 4 Project with angular 2 implemented: Solution 'Angular2Starter' |-- angular2Starter | `-- Controllers | `-- HomeController.cs |-- src | |-- app | | |-- home | | | |-- home.component.ts | ...

Creating fixed values in HTML

I need to maintain consistency in the headings of multiple tables spread across 3 HTML pages. The heading structure is as follows: <thead> <tr> <th>MyHeading</th> </tr> </thead> My goal is to store the string MyHeadin ...

Clear v-model without changing its associated values

I'm facing an issue with my <input> fields, which look like this: <input type="text" v-model=user.name" /> <input type="text" v-model="user.phone" /> <button @click="add">add user</button> Whenever the add user button i ...

Is it possible to switch the summernote editor between airmode and toolbar mode?

Currently, I am working on creating a report editor that displays only one toolbar when multiple summernote WYSIWYG editor sections are used. My solution involves having the first section as a full editor and the other section in airmode. Below is the HTM ...

Implementing a function in jQuery to create a "Check All" and "Uncheck All" button

Can someone please guide me on how to implement a check all and uncheck all functionality when I check individual checkboxes one by one? Once all checkboxes are checked, the 'checkall' checkbox should automatically be checked. Below is the code s ...

The jsonp typeahead feature is not populating the uib-typeahead form element

Trying to populate a uib-typeahead from the ui-bootstrap modules using a jsonp callback function in a factory method has been challenging. This is the factory function being used: autoCompleteCity: function(city){ return $http.jsonp("http://g ...

Identifying if a variable is redirecting

Dealing with React Router Dom V6 I am facing an issue with two loader functions that make server requests. async function fetchUserDetails(userId, userAction) { const token = getAuthToken(); const userData = await axios({ url: API.endpoint + &apos ...

Prevent tooltip text from appearing when a button is disabled in an angular application

As a beginner in UI development, I have a requirement for my Angular application. I need to enable and disable a button based on certain conditions. The tricky part is that I want to display a tooltip only when the button is enabled. I have managed to chan ...

Tips for implementing HTTP requests in Angular 2 without TypeScript

The demonstrations provided by the angular team only illustrate injecting Http for typescript. https://angular.io/docs/js/latest/api/http/Http-class.html How can this be accomplished in JavaScript? import {Http, HTTP_PROVIDERS} from 'angular2/http& ...

Malfunction in triggering events within an Ajax Magnific popup feature

I'm trying to load a page within a magnific popup using ajax: $("#operator").magnificPopup({ delegate: 'a.edit', mainClass: 'mfp-fade', closeBtnInside: true, removalDelay: 300, closeOnContentClick: false, t ...

Vue Dynamic Table Title

Is it possible to add labels to a pivot-table in Vue without affecting array indexes and drag-and-drop functionality as shown in the screenshot below? https://i.stack.imgur.com/5JTSM.png Are there alternative methods for implementing this feature? You c ...

Leveraging the value service in AngularJS

Struggling to grasp the concept of .value() and how to utilize it in controllers... Here's an example where we declare the .value() in services.js : .value("ScanDatas",{ scanData: {} }) Once "scanData" is defined, it should be available througho ...

Leveraging async/await in express

I am encountering an issue with my app.post method while trying to deploy on Firebase. The error message reads: Parsing error: Unexpected token =>. I am fairly new to node.js and Javascript as I primarily work with Swift. However, I require this code fo ...

Vue - Display components next to sidebar

Having an issue with the vue-sidebar-menu. The sidebar is appearing over the components instead of beside them. Here is a screenshot of the problem: <template> <div id="app"> <sidebar-menu :menu="menu" /> <vue-page-transit ...

Step-by-step guide on incorporating an external JavaScript library into an Ionic 3 TypeScript project

As part of a project, I am tasked with creating a custom thermostat app. While I initially wanted to use Ionic for this task, I encountered some difficulty in integrating the provided API into my project. The API.js file contains all the necessary function ...