Thursday, September 28, 2017

Loading address data into google maps from database using Angularjs

I am using angularjs for my application.I am trying to load the address from user_address table in database and display it on map on load.

Here is the script i am using to load google maps

    <script async defer src="https://maps.googleapis.com/maps/api/js?
    key=myKey&callback=initMap">
    </script>

Here is the html

    <div id="map"></div>
    <div id="repeatmap" data-ng-repeat="marker in markers | orderBy :
    'title'">
    <a id="country_container" href="#" ng-
    click="openInfoWindow($event, marker)">
    <label id="namesformap" ></label></a>
    </div>

Here is the Controller.js

    var mapOptions = {
        zoom: 4,
        center: new google.maps.LatLng(25,80),
        mapTypeId: google.maps.MapTypeId.TERRAIN
    }

    $scope.map = new google.maps.Map(document.getElementById('map'),
    mapOptions);
    $scope.markers = [];
    var infoWindow = new google.maps.InfoWindow();
    var createMarker = function (info){
    var marker = new google.maps.Marker({
            map: $scope.map,
            position: new google.maps.LatLng(info.lat, info.long),
            title: info.city
     });
     marker.content = '<div class="infoWindowContent">' + info.desc +
     '</div>';
     google.maps.event.addListener(marker, 'click', function(){
     infoWindow.setContent('<h2>' + marker.title + '</h2>' + 
     marker.content);
     infoWindow.open($scope.map, marker);
     });
     $scope.markers.push(marker);
     }  

    for (var i = 0; i < $scope.cities.length; i++){
        createMarker($scope.cities[i]);
    }

    $scope.openInfoWindow = function(e, selectedMarker){
        e.preventDefault();
        google.maps.event.trigger(selectedMarker, 'click');
    }

Here is the data that i am getting from database that is all cities from user_address table

    $scope.getAllCities = function()
    {
        DirectoryService.getAllCities().then(function(response){
        $scope.cities = response.data;
        console.log($scope.cities);
    })
    }

As you can see in console i am able to get the response from database but i am not able to get $scope.cities value to for loop.It is saying Cannot read property ‘length’ of undefined.Can anyone tell how can i get value of $scope.cities into for loop so that in map i can display the cities returned from database.Now i am able to display map but with no cities.I dont know whether it will work or not or am i doing the wrong way?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/28/loading-address-data-into-google-maps-from-database-using-angularjs/
via @lzomedia #developer #freelance #web

No comments:

Post a Comment