Is there a way to Fix a Google Maps Marker to the Center of its Map always?

前端 未结 7 1352
野趣味
野趣味 2020-12-01 00:21

To be more precise, what I try to accomplish is that while I Drag a Google Map there\'s a Google Maps Marker that stays fixed

7条回答
  •  情深已故
    2020-12-01 00:39

    You can listen to the center changes via something like below, you will just have to update your view:

    google.maps.event.addListener(map, "dragend", function() {
       console.log(map.getCenter().toUrlValue());
    });
    

    Current main used solution is for bringing up the InfoWindow only when onclick, I needed it on all the time like it is on Uber, so I replaced even the InfoWindow to a css only solution, updating the view the normal angular route with Ionic

    HTML:

     
       
    {{locationCtrl.coordinates}}

    CSS:

    #map {
     width: 100%;
     height: 100%;
    }
    #centerInfoBubble {
      position: absolute;
      /*center the marker*/
     top: 38%;
     left: 22.5%;
     z-index: 1;
     width: 50%;
     height: 6%;
     border-radius: 20px;
     border: 1px solid #111;
     background-color: #444444;
     color: #fff;
     padding: 0.5% 5%;
     cursor: pointer;
    }
    #centerMarker {
     position: absolute;
     /*url of the marker*/
     background: url(http://maps.gstatic.com/mapfiles/markers2/marker.png) no-repeat;
     /*center the marker*/
     top: 45%;
     left: 45%;
     z-index: 1;
     height: 10%;
     width: 10%;
     cursor: pointer;
    }
    

    Controller:

    myModule.controller('LocationCtrl',['$scope','$cordovaGeolocation',function($scope,$cordovaGeolocation){
    $scope.locationCtrl = {
        coordinates : null
    };
    var options = {timeout: 10000, enableHighAccuracy: true};
    var marker;
    
    $cordovaGeolocation.getCurrentPosition(options).then(function(position){
    
        var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    
        var mapOptions = {
                center : latLng,
                zoom : 16,
                mapTypeId : google.maps.MapTypeId.ROADMAP,
                mapTypeControl : false,
                streetViewControl : false,
                zoomControl : false
        };
    
        $scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
        $scope.locationCtrl.coordinates = $scope.map.getCenter().toUrlValue();
    
        google.maps.event.addListener($scope.map, "dragend", function() {
            $scope.locationCtrl.coordinates = $scope.map.getCenter().toUrlValue();
            $scope.$apply();
        });
    
    }, function(error){
    console.log("Could not get location");
    });
    
    }]);
    

    I don't know if there are performance issues with this yet, but looks quite smooth on the device, hope it helps someone

提交回复
热议问题