What is the process for adding a marker to an Angular Google Map using the autocomplete feature?

Can anyone help me with adding a marker on Google Angular Map using autocomplete search? I am able to retrieve the location in terms of latitude and longitude, but there seems to be an issue with adding the marker. Please review my code below:

Controller code:

$timeout(function() {

          var input = document.getElementById('pac-input');
          var searchBox = new google.maps.places.SearchBox(input);

          google.maps.event.addListener(searchBox, 'places_changed', function() {
             var marker= [] ;
             var places = searchBox.getPlaces();

             if (places.length == 0) {
               return;
             }

            var loc_data = {            

              coords: {
                  latitude: places[0].geometry.location.lat(),
                  longitude: places[0].geometry.location.lng()
              }
            };
            marker.push(loc_data);
            $scope.markers=marker;              
          });

HTML code:

    <ui-gmap-markers models="markers" idkey="markers.id" coords="'coords'" >

    </ui-gmap-markers>

<div class="col-md-4">

    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
</div>

Answer №1

 <div class="form-group">
                                <label for="pacinput" class="control-label col-md-4">Location Search</label>
                                <div class="col-md-8">
                                    <input id="pacinput" class="form-control" type="text" placeholder="Search Location">
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="col-md-offset-4 col-md-8">
                                    <asp:HiddenField runat="server" ID="address" />
                                    <asp:HiddenField ID="txtLat" runat="server" />
                                    <asp:HiddenField ID="txtLng" runat="server" />
                                    <div id="map" style="width: 100%; height: 380px;">
                                    </div>
                                </div>
                            </div>

// This instance introduces a search input on a map, utilizing Google Place Autocomplete // feature for geographical searches. Users can enter locations in the search box and it will return // suggestions containing places or predicted terms.

    // To use this functionality, ensure to include the Places library. Add libraries=places
    // parameter when initially loading the API like:
    // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

    function initAutocomplete() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: 15.362813, lng: 75.126129 },
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        // Create the search box and link it to the UI element.
        var input = document.getElementById('pacinput');
        var searchBox = new google.maps.places.SearchBox(input);

        // Adjust the SearchBox results based on the current viewport of the map.
        map.addListener('bounds_changed', function () {
            searchBox.setBounds(map.getBounds());
        });

        var markers = [];
        // Listen for user selection event and fetch more details about the place.
        searchBox.addListener('places_changed', function () {
            var places = searchBox.getPlaces();

            if (places.length == 0) {
                return;
            }

            // Clear previous markers.
            markers.forEach(function (marker) {
                marker.setMap(null);
            });
            markers = [];

            // Get icon, name, and location for each place.
            var bounds = new google.maps.LatLngBounds();
            places.forEach(function (place) {
                var icon = {
                    url: place.icon,
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(25, 25)
                };

                // Generate marker for each place.
                markers.push(new google.maps.Marker({
                    map: map,
                    icon: icon,
                    title: place.name,
                    position: place.geometry.location
                }));

                if (place.geometry.viewport) {
                    // Check if there's a viewport available.
                    bounds.union(place.geometry.viewport);
                } else {
                    bounds.extend(place.geometry.location);
                }
            });
            map.fitBounds(bounds);
        });
    }

</script>

Answer №2

To display a location on your map, you'll need to generate a marker.

let newMarker = new google.maps.Marker({
          position: locationData.coordinates,
          map: mapID
        });

If you'd like to include an animated drop effect or event listeners:

   newMarker.setAnimation(google.maps.Animation.DROP);
   newMarker.addListener('click', clickHandlerFunction);

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

"Embedding social content within an iframe may result in the element being unresponsive

I have a setup where I'm utilizing social embed to include Instagram content in the footer. When I insert the provided iframe code, the layout looks correct but the content is not clickable. <iframe src="https://embedsocial.com/facebook_album ...

Consistently obtaining the same outcome in JavaScript, always

Is it possible to resolve this issue? I keep getting a result of less than 18 when trying numbers 1-100, even though the output should be for values under 18. In my HTML code, there is a <p> element with id="result", an input with id=&quo ...

Fixing Typescript assignment error: "Error parsing module"

Trying to assign an object to the variable initialState, where the type of selectedActivity is Activity | undefined. After using the Nullish Coalescing operator (??), the type of emptyActivity becomes Activity. However, upon execution of this line, an err ...

Having difficulty accessing information from Firebase database using the .once() function

When a button is clicked on the page, I need to fetch data from a Firebase database using the once() function. Despite setting up the necessary references and variables, the data retrieval seems to be unsuccessful as the global variable numElections keeps ...

What is the best way to send information back to an AJAX script that has made a

Can someone explain to me how the response section of an AJAX call is processed and formatted using plain, native JavaScript (no jQuery or other frameworks)? I have searched extensively but have not found a clear answer. I am looking for an example that ...

When using jQuery with a large selectbox, you may encounter the error message: "Uncaught RangeError: Maximum

My select box works fine in IE and Mozilla, but throws an uncaught rangeError in Chrome when choosing the "Others" option to display a second select box with over 10k options. How can I diagnose and resolve this issue? <!DOCTYPE html> ...

What could be the reason for the child event not updating the state in the parent component (Vue)?

I have a component called customize-charts which contains a Vuetify drawer: <template> <v-col> <v-btn style="float: right" class="mr-4 mt-2" small @click="toggleCustomize" v-if="!open">Custom ...

Tips for hiding specific rows in ng-grid

I'm working with an array of objects that I need to display in ng-grid. Each object in the array has a boolean property called isVisible. My goal is to only show the rows where isVisible is true, while completely hiding the rows where it is false. So ...

Move divs that are currently not visible on the screen to a new position using CSS animations

Upon entering the site, I would like certain divs to animate from an offscreen position. I came across this code snippet: $( document ).ready(function() { $('.box-wrapper').each(function(index, element) { setTimeout(function(){ ...

How can we avoid images from collapsing when we close the side navigation?

Is there a way to prevent my image from shrinking gradually when I close my side navigation? I used an example from w3schools for a basic side navigation that slowly transitions its width to 0px when closed. However, I noticed that the image I added to t ...

Display the username on a Meteor React component

I'm facing an issue with one of my React components, which serves as the main layout for my application. It includes a navigation bar that displays the username of the currently logged-in user. The problem arises when Meteor.user() returns undefined d ...

Attaching identical class and event handlers to numerous dynamically created elements

I am facing a challenge with the following HTML structure: <a href="#" @click.prevent="toggleClass">Show/Hide</a><br> <li :class="{myClass: showItems}">Item 1</li> <a href="#" @click.prevent="toggleClass">Show/Hide< ...

Changing the content of a <div> element using the information retrieved from the previous page

When the user clicks the "Edit" button, I am redirecting them from another page using the following code snippet. $('#editListButton').click(function(){ window.location.href = "http://localhost/yyy.php"; //redirect // Modifications th ...

Tips on locating file encoding and decoding?

I have been tasked with understanding the decoding process of a file left on my system by Spotify. The specific file is named context_player_state_restore and can be found in the directory /Users/<myuser>/Library/Application Support/Spotify/Persiste ...

Step-by-step guide for deploying a full-stack application to Heroku or Netlify: What essential files do you need?

When my full-stack app runs perfectly on LocalHost but fails to function properly once deployed on Heroku or netlify, what changes are required to ensure the backend works seamlessly and continues interfacing with the API for frontend updates? I have attem ...

How do I preserve data within $scope upon switching views using ng-include?

Can you please take a look at this jsFiddle? http://jsfiddle.net/mystikacid/b7hqcdfk/4/ This is the template code: <div ng-app="myApp"> <div ng-controller="dataCtrl"> <div>Data : {{data}} (Value outside views)</div> < ...

Troubleshooting: Resolving issues with Vue's global EventBus in my project

I am using Vue.js within a Laravel project and I am encountering an issue with the global event bus. I have created an event-bus.js file and imported it where needed. Although events are being generated upon clicking, there seems to be no reactions from th ...

Tips for preserving the state of the Material-UI AutoComplete during component re-renders?

Currently, I am utilizing the Material-UI v4 AutoComplete component along with the renderOption prop in order to display a checkbox item option. The issue arises when the onChange event occurs and updates a hook in the parent component causing a re-rende ...

Creating a customized navigation bar with a unique menu list underline feature using JavaScript

I recently created a customized navbar using a script to add a hover effect to the menu links. You can find the script I used here: https://github.com/shadeed/underliner. Although I was able to get it partially working, there are still some issues. The we ...

Prevent certain images from loading by blocking them

I am trying to create an extension that blocks two specific images from loading. Initially, I attempted to achieve this by using the following code in the content.js file: $("#rated-image").remove(); //id of one image $(".blur-mask").remove(); //class of ...