Search code examples
angularjsgoogle-mapsdrop-down-menung-optionscity

Draw map based on selected city in selectbox in angularjs


i have a select box for city which has number of cities getting through ng-options. i need to show the map on the website based on city selected in the selectbox.
this is how i am getting city names

// Code goes here


$scope.data = [{
        cities: [{
            id: 1,
            title: 'Mysore'
        }, {
            id: 2,
            title: 'Bangalore'
        }, {
            id: 3,
            title: 'Delhi'
        }, {
            id: 4,
            title: 'Mumbai'
        }],
        maps: [{
                id: 1,
                title: 'Zoo',
                city_id: 1
            }, {
                id: 2,
                title: 'Palace',
                city_id: 1
            }, {
                id: 3,
                title: 'Beach',
                city_id: 4
            }]

    }];
});

Plunker here https://plnkr.co/edit/r1S1e61H3RfH3uYGYTBP?p=preview
Can anyone please help me.


Solution

  • Move the coordinates to the $scope:

    $scope.coordinates = {
      lat: 28.620089858889145,
      lng: 77.17483520507812
    };
    

    And:

    <ng-map zoom="13" center="{{coordinates.lat}},{{coordinates.lng}}" ...
    

    Use ng-change on the select:

    ng-change="centerCity(citySelect.selectedOption)"
    

    In the centerCity method you can use the geocoder to retrieve the coordinates by city name. Then you simply need to update the variables.

    Simple example:

    var geocoder = new google.maps.Geocoder();
    
    $scope.centerCity = function(city) {
    
      geocoder.geocode({
        'address': city.title
      }, function(results, status) {
    
        if (status == google.maps.GeocoderStatus.OK) {
    
          $scope.$apply(function() {
            $scope.coordinates.lat = results[0].geometry.location.lat();
            $scope.coordinates.lng= results[0].geometry.location.lng();
          });
    
        } else {
          console.log('Error');
        }
      });
    };
    

    Demo: https://plnkr.co/edit/WETs0FL0DbPbDn2A77hq?p=preview