How do I add markers to a Google Map?

丶灬走出姿态 提交于 2020-01-02 20:08:33

问题


I am trying to have an input field that when submitted adds a marker to my Google Map. Right now when I submit the field it is creating the object but the marker is not being displayed. Right now I am able to get a location to show up if it is hard coded in but not when I add a new one. (I know that the view right now is only for the hard coded one, I have that so the current code is working)

Here is my code:

My View:

<form>
  <input type="number" class="" ng-model="marker.markerLat" required="">
  <input type="number" class="" ng-model="marker.markerLng" required="">
  <button class="button" ng-click="addMarker(marker)">Add</button>
</form>
<google-map center="map.center" zoom="map.zoom">
 <marker coords="marker.coords" options="marker.options" idkey="marker.id" >
 </marker>
</google-map>

My Controller:

//Default location
        $scope.map = {
          center: {
            latitude: 32.7833,
            longitude: -79.9333
          },
          zoom: 11
        }
        $scope.options = {scrollwheel: true};

        $scope.markers = [];

        $scope.addMarker = function (marker) {

            $scope.markers.push({
                latitude: parseFloat($scope.markerLat),
                longitude: parseFloat($scope.markerLng)
            });

            console.log('Maker add: ' + $scope.markers);
            $scope.markerLat ="";
            $scope.markerLng ="";
        };

        $scope.marker = {
          id:0,
          coords: {
            latitude: 32.7833,
            longitude: -79.9333
          }
          }

回答1:


I would advice you to create a custom angular directive for your map.

But anyway, angular is not enough to get what you want working. You have to create google.maps objects. And set the map property of your marker to the map you have created.

Here is a little example :

.directive('map', function () {
return {
  template: '<div></div>',
  restrict: 'EA',
  replace: true,
  link: function (scope, element) {

    scope.markers = [];

    scope.map = new google.maps.Map(element[0], {
      center: new google.maps.LatLng(32.7833, -79.9333),
      zoom: 11
    });

    scope.addMarker = function (lat, lnt) {
      var marker = new google.maps.Marker({
        map: scope.map,
        position:  new google.maps.LatLng(lat, lng)
      });

      scope.markers.push(marker);
    };

  }
});

So you simply have to call the addMarker function with a lat and lng parameter. Use angular events to communicate between your controller and directive. More info about the methods here



来源:https://stackoverflow.com/questions/26023789/how-do-i-add-markers-to-a-google-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!