Show the details of a location directly on Google Maps API marker

I am currently developing a project using AngularJs, where I am displaying information on a Google Maps interface. You can check out my example on this plunker link.

My goal is to retrieve the 'city' and 'desc' fields by clicking on the map markers.

Here is a snippet of the controller code:

var cities = [{
    city: 'mourouj5',
    desc: 'This is the best city in the world!'

}, {
    city: 'New York',
    desc: 'This city is aiiiiite!'

}, {
    city: 'tokyo',
    desc: 'This is the second best city in the world!'

}, {
    city: 'Paris',
    desc: 'This city is live!'

}, {
    city: 'barcelone',
    desc: 'Sin City...\'nuff said!',

}];

angular.module('mapsApp', [])
    .controller('MapCtrl', function($scope) {

        var map = new google.maps.Map(document.getElementById('map'), {
            mapTypeId: google.maps.MapTypeId.TERRAIN,
            center: new google.maps.LatLng(40.0000, -98.0000),
            zoom: 2
        });

        var createMarker = function(info) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({
                    'address': info.city
                },
                function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        var marker = new google.maps.Marker({
                            position: results[0].geometry.location,
                            map: map,
                            title: info.city
                        });
                        marker.content = '<div class="infoWindowContent">' + info.desc + '</div>';

                        google.maps.event.addListener(marker, 'click', function() {
                            infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
                            infoWindow.open($scope.map, marker);
                        });
                        $scope.markers.push(marker);
                    }
                });
        }

        for (var i = 0; i < cities.length; i++) {
            createMarker(cities[i]);
        }

    });

Answer №1

Check out this functional example:

var cities = [{
    city: 'mourouj',
    desc: 'This city is known as the best in the world!'

}, {
    city: 'New York',
    desc: 'Not too bad, right?'

}, {
    city: 'tokyo',
    desc: 'Considered the second best city globally.'

}, {
    city: 'Paris',
    desc: 'The city of love and lights!'

}, {
    city: 'barcelone',
    desc: 'Sin City...enough said.',

}];


angular.module('mapsApp', [])
    .controller('MapCtrl', function ($scope) {

        $scope.markers = [];

        $scope.map = new google.maps.Map(document.getElementById('map'), {
            mapTypeId: google.maps.MapTypeId.TERRAIN,
            center: new google.maps.LatLng(40.0000, -98.0000),
            zoom: 2
        });

        $scope.infoWindow = new google.maps.InfoWindow({});

        $scope.createMarker = function (info) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({
                'address': info.city
            },
                function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        var marker = new google.maps.Marker({
                            position: results[0].geometry.location,
                            map: $scope.map,
                            title: info.city,
                            content: '<div class="infoWindowContent">' + info.desc + '</div>'
                        });


                        google.maps.event.addListener(marker, 'click', function() {
                            $scope.infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
                            $scope.infoWindow.open($scope.map, marker);
                        });
                        $scope.markers.push(marker);
                    }

                });
        }

        for (i = 0; i < cities.length; i++) {
            $scope.createMarker(cities[i]);
        }


    });
<script src="https://code.angularjs.org/1.3.14/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=&sensor=false&extension=.js"></script>
<script src="http://rawgit.com/angular-ui/angular-google-maps/2.0.X/dist/angular-google-maps.js"></script>
<body ng-app="mapsApp" ng-controller="MapCtrl">
    <div id="map" style="width: 700px; height: 700px;"></div>
</body>
   

Answer №2

An easy fix that involves updating the createMarker function:

let updateMarker = function(data) {
                let geocoder = new google.maps.Geocoder();
                geocoder.geocode({
                    'address': data.location
                },
                function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {

                        let marker = new google.maps.Marker({
                            position: results[0].geometry.location,
                            map: map,
                            title: data.city
                        });}

                        let contentWindow = new google.maps.InfoWindow({
                          content:data.description
                        });
                        google.maps.event.addListener(marker,'click',function() {
                           contentWindow.open(map,marker);
                        });

                });
            }

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

Incorporate a line break between the day and month on your JQuery datepicker

Is it possible to insert a line break or some other element between the day and month in the input field when using JQuery datepicker? Here is the current code I have: jQuery('#checkin').datepicker({ showAnim: "drop", dateFormat ...

Adding HTML code directly at the cursor location within a contenteditable element

On button click, I need to insert an element at a specific position within a contenteditable div. Currently, the content is added at the end of the document instead of where the cursor was placed before clicking the button. function append_content() { ...

Transmit the Angular data model to the server

Whenever any of the inputs change, this function is triggered: $scope.updateOutputData = function(){ // Collecting input data and creating object $scope.selectionObject = { "departure_city" : departureCityDigest, "departure_country" : ...

What is the best way to create a layout with two images positioned in the center?

Is it possible to align the two pictures to the center of the page horizontally using only HTML and CSS? I've tried using this code but it doesn't seem to work: #product .container { display: flex; justify-content: space-between; flex-w ...

We are currently experiencing issues with Internet Explorer retrieving data from input type text

My HTML code includes input elements with type="text" like this: <input type="text" class="f_taskname" value=""/> Once the user enters text and hits enter, the following script is triggered: var task_name=$('#filter_body').find('.f_ ...

Tips for transferring an image to an FTP server using an FTP client without using multipart uploading methods

I am currently working on uploading an image to my FTP server. I have successfully retrieved the image and obtained its location at file:///storage/sdcard0/Android/data/com.ionicframework.ftptranfer949961/cache/1467013143014.png The image file I need to s ...

What is the best way to display the next and restart buttons at the bottom of every question?

How can I display the next and restart buttons at the bottom of each question in my JavaScript quiz web app? Why is the user unable to choose the wrong answer from the provided options? I'm facing difficulty showing the next and restart buttons for i ...

Comparing Canvas and CSS3 for Website Development

Many discussions focus on comparing games with high levels of interaction, but my project involves a web application that manipulates objects individually. These objects can be images or text, and they can be replaced, resized, rotated, zoomed in, and dele ...

Neglecting asynchronous Ajax functions once they have been called

I currently have a function that looks like this: $("#transfer").click(function(){ var token_rec = $("#token_rec").val(); var user_rec = $("#user_rec").val(); var subdomain_rec = $("#subdominio_rec").val(); var req_rec ...

Ever since I switched to a different monitor, my Javascript has suddenly stopped functioning

I'm encountering an issue where my JS stops working every time I switch displays within a single HTML file. I've attempted to replace the HTML onclick call with a JavaScript function, but the problem persists. Update: Apologies for the unclear e ...

jQuery if statement appears to be malfunctioning

When the condition operates alone, everything works fine. However, when I introduce an 'and' operation, it does not function correctly. If only one of them is true, the code works. It also successfully takes input values. <!DOCTYPE HTML Code ...

Is there a more efficient method for handling this JSON dataset?

After delving into Sitepoint's "Novice to Ninja" and starting to explore jQuery, I can't help but question if there is a more efficient way to write the code I've put together. The resounding answer appears to be "yes." All these cumbersome ...

Ensuring a button (class) is in active hover mode when the document loads

My website features 4 clickable service buttons on the homepage, each with a unique hover effect (background-color change) when users interact with them. While this setup works well overall, I am looking to highlight the FIRST button as the most important ...

Tips for creating a stylish ReactJs Header component that stays fixed at the top of the page

Having an issue with my Header component - I want it to remain fixed at the top while scrolling down. Here's the current code: I've attempted using "position = fixed", but it caused my header to resize. Then, I tried setting its width to "width ...

The message from the XHR Object appears to be undefined, yet it correctly displays the status

I am currently working on an ajax call that is expected to return a 400 http error code. The backend language being used is PHP. Here is my PHP code: header('Content-Type: text/html',true,400); echo $this->upload->display_errors('< ...

Can you interact with a node within an Electron application even if the node integration feature is not enabled?

I have an electron app created with vanilla electron. (using npx create-electron-app ......) Can I use const electron = require("electron"); with nodeintegration:true? The library I'm using does not support nodeintegration:true, but my scr ...

Checking the content of a textfield in React Material UI based on the user input

Hello! I am seeking a solution to trigger an error message whenever the value entered in the first text field is not equal to "28.71", otherwise display a correct message. Here is my current code: class Main extends React.PureComponent { render() { ...

A more concise approach to crafting ajax requests

Lately, I've been immersed in building various web applications using php, mysql, jquery, and bootstrap. Now, I'm faced with a common issue - how to streamline my ajax queries for posting data? Writing code that is not only functional but also a ...

The request for http://localhost:3000/insert.js was terminated due to a 404 (Not Found) error

As someone new to web development, I am currently tackling a project where I'm having trouble loading the Javascript file insert.js. The HTML document upload.html resides in the public folder, while the Javascript file is located in the main folder. I ...

Creating a custom filter

I am working on creating a filter and I could use some assistance with making minimal changes to my code. I am confident that there is a practical solution for what I am trying to achieve and would appreciate any corrections or suggestions. Button01' ...