24sharon 24sharon - 1 month ago 39
AngularJS Question

Angular google map marker

I add google map with marker on load the marker set up to center,

But when the user change the zoom or move right left the map, the marker position change and the marker move to center and not the same of the coords that i add on page load

this is my code:

<ui-gmap-google-map center="map.center" zoom="map.zoom" draggable="false" options="options">
<ui-gmap-marker idkey="'1'" coords='map.center'
icon='{url: "//developers.google.com/.../beachflag.png" }'>
<ui-gmap-window isiconvisibleonclick="true">
<p ng-cloak>Marker Clicked!</p>
</ui-gmap-window>
</ui-gmap-marker>
</ui-gmap-google-map>


this is my map object

enter image description here

My Problem same as here:
Angular google map marker position not fixed, moving when map moves. How to make marker static?

How can i add marker that fixed on place and if the user move left right or zoom the map the marker stay on the same original coords.

Thanks

Answer

Your problem is that the ui-gmap-marker coords attribute is a reference to map.center, which changes whenever you move the map. You'll want to have an own controller variable for the marker, so it has its own location attribute. Something like this,

Controller:

// Map initialization
$scope.map = { center: { latitude: 32.0889, longitude: 34.8357 }, zoom: 16};

// Give the marker its own scope variable, you can attach other info here, too
$scope.marker = {coords: angular.copy($scope.map.center)}

HTML:

<ui-gmap-google-map center="map.center" zoom="map.zoom" draggable="false" options="options">
    <ui-gmap-marker idkey="'1'"  coords='marker.coords'
        icon='{url:    "//developers.google.com/.../beachflag.png" }'>
        <ui-gmap-window isiconvisibleonclick="true">
            <p ng-cloak>Marker Clicked!</p>
        </ui-gmap-window>
    </ui-gmap-marker>
</ui-gmap-google-map>

EDIT: Forgot angular.copy first. Added plunkers demonstrating both broken and working behaviour.

Broken: http://plnkr.co/edit/nkecrOXm84V6lEVr85Yi?p=preview

Working: http://plnkr.co/edit/kvgLSeuKTPo6FKqIFE89?p=preview