Tad Scritchfield
Tad Scritchfield

Reputation: 85

Angular Google Maps map click event works once

I've been having a problem very similar to this

However that persons question was never answered and my situation is subtly different.

I'm trying to add a click event to my map that will change the center of the map to the location of the click. My code to do this works great, but it only works once and then when I click again I get this error:

angular-google-maps.js:6815 Uncaught TypeError: Cannot read property 'click' of undefined

Here is my map object:

vm.map = {
     center: {
          latitude: l.latitude,
          longitude: l.longitude
     },
     zoom: 13,
     events: {
          click: function(map, event, coords) {
               vm.map = {
                    center: {
                         latitude: coords[0].latLng.lat(),
                         longitude: coords[0].latLng.lng()
                    },
               };

               $scope.apply();

           }
     }
};

And here's my html:

<ui-gmap-google-map center="location.map.center" zoom="location.map.zoom" draggable="true" options="tabLocations.map.options" events=location.map.events>
    <ui-gmap-search-box template="'scripts/components/tab-locations/searchbox.tpl.html'" events="location.map.searchbox.events" parentdiv="'searchbox-container'"></ui-gmap-search-box>
    <ui-gmap-marker ng-if="location.active" idKey="1" coords="location" options="{draggable: false, icon: 'images/icons/gps-marker-active.svg'}"></ui-gmap-marker>
    <ui-gmap-marker ng-if="!location.active" idKey="1" coords="location" options="{draggable: false, icon: 'images/icons/gps-marker-inactive.svg'}"></ui-gmap-marker>
</ui-gmap-google-map>

Upvotes: 2

Views: 688

Answers (1)

theblindprophet
theblindprophet

Reputation: 7927

After your first click you are redefining a brand new map with no click event:

vm.map = {
    center: {
        latitude: coords[0].latLng.lat(),
        longitude: coords[0].latLng.lng()
    },
};

This is overriding all the previous properties you had set before, which includes click.

Use setCenter instead:

click: function(map, event, coords) {

    var latLng = new google.maps.LatLng(latitude: coords[0].latLng.lat(), latitude: coords[0].latLng.lng());
    vm.map.setCenter(latLng);

}

Reference: Google Maps API

Upvotes: 1

Related Questions