user4046743
user4046743

Reputation:

Add Marker in Angular-Google-Maps

I'm currently having some trouble adding a marker on click to Google Maps. I'm using http://angular-ui.github.io .

Here is my code: HTML:

<ui-gmap-google-map center='map.center' zoom='map.zoom' events="map.events">
  <ui-gmap-marker coords="map.marker.coords" idKey="map.marker.id"></ui-gmap-marker>
</ui-gmap-google-map>

And there is my JS:

$scope.map = {
    center: {
        latitude: alat.value, longitude: alon.value },
        zoom: 15,
        streetViewControl: false,
        events: {
            click: function (map, eventName, originalEventArgs) {
                var e = originalEventArgs[0];
                var lat = e.latLng.lat(),lon = e.latLng.lng();
                $scope.map.marker = {
                    id: 1,
                    coords: {
                        latitude: lat,
                        longitude: lon
                    }
                };
                $scope.$apply();
            }
        }
    };

I've been following the Angular-Google-Maps API, but I'm not entirely excellent at the Google Maps API as yet. So far, I've deduced that my click event does work, but my marker is not being added to the map. Help would be appreciated.

Upvotes: 12

Views: 20712

Answers (2)

rxing
rxing

Reputation: 373

It seems you need give $scope.map.marker.id one init value. Otherwise, below error would occur.

gMarker.key undefined and it is REQUIRED!!

Upvotes: 5

Jayram
Jayram

Reputation: 19588

I have created the fiddle. Here is the HTML.

<div ng-app="main" ng-controller="mainCtrl">
    <ui-gmap-google-map center="map.center" zoom="map.zoom" draggable="true" events="map.events">
        <ui-gmap-marker ng-repeat="m in map.markers" coords="m.coords" icon="m.icon" idkey="m.id"></ui-gmap-marker>
    </ui-gmap-google-map>
</div>

The controller is like this.

angular.module('main', ['uiGmapgoogle-maps'])
.controller('mainCtrl', function ($scope) {

    angular.extend($scope, {
        map: {
            center: {
                latitude: 42.3349940452867,
                longitude:-71.0353168884369
            },
            zoom: 11,
            markers: [],
            events: {
            click: function (map, eventName, originalEventArgs) {
                var e = originalEventArgs[0];
                var lat = e.latLng.lat(),lon = e.latLng.lng();
                var marker = {
                    id: Date.now(),
                    coords: {
                        latitude: lat,
                        longitude: lon
                    }
                };
                $scope.map.markers.push(marker);
                console.log($scope.map.markers);
                $scope.$apply();
            }
        }
        }
    });
});

Upvotes: 16

Related Questions