angular-google-maps not rendering map, just the map controls - angularjs

My map is only partially loading the map controls but not rendering the actual map:
I have all of the proper dependencies loaded, using this as a guideline.
my HTML:
<div class="col-xs-3">
<ui-gmap-google-map center="vm.map.center" zoom="vm.map.zoom">
<ui-gmap-layer type="TrafficLayer" show="vm.map.showTraffic"></ui-gmap-layer>
</ui-gmap-google-map>
</div>
I am using the recommended uiGmapGoogleMapApiProvider provider to guarantee that angular-google-maps does not begin processing any directives until all of the Google Maps SDK is fully ready:
angular.module('app', [
'uiGmapgoogle-maps',
]).config(config)
config.$inject = ['uiGmapGoogleMapApiProvider'];
function config(uiGmapGoogleMapApiProvider) {
uiGmapGoogleMapApiProvider.configure({
v: '3.17',
libraries: 'weather,geometry,visualizations'
})
}
And My angular map model inside my controller:
uiGmapGoogleMapApi.then(function(maps) {
console.log(maps, "MAPS");
vm.map = {center: {latitude: 45, logitude: -73}, zoom:8, showTraffic: true, show: true}
})
Why is my map detail not showing up?
Thank you!

added some base options and wa-lah!
uiGmapGoogleMapApi.then(function(maps) {
console.log(maps, "MAPS");
var baseOptions = {
'maxZoom': 15,
'minZoom': 4,
'backgroundColor': '#b0d1d4',
'panControl': false,
'zoomControl': true,
'draggable': true,
'zoomControlOptions': {
'position': 'RIGHT_TOP',
'style': 'SMALL'
}
};
console.log("here")
vm.map = {center: {latitude: 51.219053, longitude: 4.404418}, options:baseOptions, zoom:8, showTraffic: true, show: true}
})

Related

AngularJS: Route displaying blank page

I have a route/view that is displaying a blank page. I am pretty sure it was working the way I have it right now a few days ago which leads me to think it is a problem with my Google Maps API key, but there are no errors or warnings so I think it has to do with my routing setup. But I have another view set up exactly the same way and that one does work...
Broken view: http://alainwebdesign.ca/pl2/#/49.2/-122.66
Working view: http://alainwebdesign.ca/pl2/#/getLocation
Controller (I commented out the.config for Google Map API because I have a script reference in my view searchRadius.html) :
(function (window, ng) {
ng.module('app', ['uiGmapgoogle-maps', 'ui.router'])
.config(function ($stateProvider) { //had: , $stateChangeError included in the function parameters, but that caused error
$stateProvider.state('searchRadius', {
url: '/:lat/:lon',
templateUrl: 'searchRadius.html', //changed from index to searchRadius.html
controller: 'MapsCtrl',
});
})
////ALREADY HAVE GOOGLE MAPS KEY ON searchRadius.html
.config(['uiGmapGoogleMapApiProvider', function (GoogleMapApi) {
GoogleMapApi.configure({
key: 'AIzaSyC_XEbbw3sNm4XlLAgqMJTggeHLDUdV-pY',
v: '3',
libraries: 'weather,geometry,visualization'
});
} ])
.controller('MapsCtrl', ['$scope', "uiGmapLogger", "uiGmapGoogleMapApi", "$interval", "$state", "$stateParams",
function ($scope, $log, GoogleMapApi, $interval, $state, $stateParams) {
$log.currentLevel = $log.LEVELS.debug;
var center = { latitude: parseFloat($stateParams.lat), longitude: parseFloat($stateParams.lon) };
alert(JSON.stringify(center));
Object.freeze(center); //caused TypeError: Cannot assign to read only property ('latitude') ...
console.log($stateParams);
$scope.map = {
center: center,
pan: false,
zoom: 16,
refresh: false,
events: {},
bounds: {}
};
$scope.map.circle = {
id: 1,
center: center,
radius: 500, //(current time - date lost)*km/hour
stroke: {
color: '#08B21F',
weight: 2,
opacity: 1
},
fill: {
color: '#08B21F',
opacity: 0.5
},
geodesic: false, // optional: defaults to false
draggable: false, // optional: defaults to false
clickable: true, // optional: defaults to true
editable: false, // optional: defaults to false
visible: true, // optional: defaults to true
events: {
dblclick: function () {
$log.debug("circle dblclick");
},
radius_changed: function (gObject) {
var radius = gObject.getRadius();
$log.debug("circle radius radius_changed " + radius);
}
}
}
//Increase Radius:
$interval(function(){
$scope.map.circle.radius += 30; //dynamic var
}, 1000); //end of interval function
} ]); //end of controller
})(window, angular);
searchRadius.html:
<div style="height: 100%"> <!--took out: ng-if="map.center !== undefined"-->
<ui-gmap-google-map
center='map.center'
zoom='map.zoom'
draggable='map.draggable'
dragging='map.dragging'
refresh='map.refresh'
options='map.options'
events='map.events'
pan='map.pan'>
<ui-gmap-circle
center='map.circle.center'
radius='map.circle.radius'
fill='map.circle.fill'
stroke='map.circle.stroke'
clickable='map.circle.clickable'
draggable='map.circle.draggable'
editable='map.circle.editable'
visible='map.circle.visible'
events='map.circle.events'>
</ui-gmap-circle>
</ui-gmap-google-map>
<script src='//maps.googleapis.com/maps/api/js?key=AIzaSyC_XEbbw3sNm4XlLAgqMJTggeHLDUdV-pY'></script>
</div>
Combine the 2 files into 1 file and initialize the $stateProvider in a single line.

Angular Google Maps Polyline Coordinates from Database

I am trying to display a Polyline on an Ionic application using Angular Google Maps with coordinates from a database. I read the documentation on the Angular Google Maps site regarding getting the coordinates and attempting to create the path via the coordinates from an API. I tried using Angular.forEach to use checklat and checklong as my coordinates but it doesn't show anything on the map. How can I use the coordinates on the data below to display as a polyline?
Data from API:
_id "57393e042613d90300a35a0a"
tripstatus "1"
tripcreated "1463367863236"
tripdescription "testing one two three. i am ironman."
tripname "New trip to test user current trip"
__v 0
checks
0 checklat " 10.72403187357376"
checklong "122.53443290985284"
time "1463367863236"
_id "57394ae62613d90300a35a10"
1 checklat "10.724010661667863"
checklong "122.53442867631733"
time "1463367863236"
_id "57394b272613d90300a35a16"
2 checklat "10.6817828"
checklong "122.5389465"
time "1463367863236"
_id "57394c662613d90300a35a1a"
My Controller:
TripFac.getTrip(id).success(function(data) {
$scope.trips = data;
var latlng = data[0].checks;
angular.forEach(latlng, function(path) {
path = {
latitude: checklat,
longitude: checklong
}
});
$scope.latlng = latlng;
});
//Get Trip Points and put on polyline
$scope.polylines = [];
uiGmapGoogleMapApi.then(function(){
$scope.polylines = [
{
path: latlng,
stroke: {
color: '#6060FB',
weight: 3
},
geodesic: true,
visible: true,
icons: [{
icon: {
path: google.maps.SymbolPath.BACKWARD_OPEN_ARROW
},
offset: '25px',
repeat: '50px'
}]
}
];
});
My view:
<ui-gmap-google-map
center="map.center"
zoom="map.zoom"
id="wrapper">
<style>
.angular-google-map-container { height:450px; width:auto; }
</style>
<ui-gmap-polyline ng-repeat="p in polylines" path="p.path" stroke="p.stroke" visible='p.visible' geodesic='p.geodesic' fit="false" editable="p.editable" draggable="p.draggable" icons='p.icons'></ui-gmap-polyline>
</ui-gmap-google-map>
Foe example
$scope.map.center = {
latitude: $scope.latitude,
longitude: $scope.longitude
};
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var directionsService = new google.maps.DirectionsService();
$scope.directions = {
origin: new google.maps.LatLng($scope.lat, $scope.lng),
destination: new google.maps.LatLng($scope.latitude, $scope.longitude),
showList: false
}
var request = {
origin: $scope.directions.origin,
destination: $scope.directions.destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setMap($scope.map.control.getGMap());
} else {}
});
It could be related with one of the following reasons:
undefined latlng object is passed into $scope.polylines, needs to be changed to $scope.latlng
$scope.polylines could be initialized before json data is getting loaded
The following example demonstrates how to load data from external source and initialize a polygon(s) on the map:
angular.module('map-example', ['uiGmapgoogle-maps'])
.controller('MapController', function($scope, $http, uiGmapGoogleMapApi, uiGmapIsReady) {
$scope.map = {
zoom: 12,
bounds: {},
center: { latitude: 10.6817828, longitude: 122.53443290985284 }
};
var loadPathData = function() {
return $http.get('https://rawgit.com/vgrem/3fc4ffc90de778f38f09b671466001fa/raw/8da45ddf4b174d758892e8a6514fea9145f4b91b/data.json')
.then(function(res) {
//extract data
return res.data[0].checks.map(function(item) {
return {
latitude: item.checklat,
longitude: item.checklong
}
});
});
};
var drawPolylines = function(path) {
$scope.polylines = [
{
path: path,
stroke: {
color: '#6060FB',
weight: 3
},
geodesic: true,
visible: true,
icons: [{
icon: {
path: google.maps.SymbolPath.BACKWARD_OPEN_ARROW
},
offset: '25px',
repeat: '50px'
}]
}
];
}
uiGmapIsReady.promise()
.then(function(instances) {
loadPathData()
.then(drawPolylines);
});
});
.angular-google-map-container {
height: 450px;
width: auto;
}
<div ng-app="map-example" ng-controller="MapController">
<ui-gmap-google-map center="map.center" zoom="map.zoom" id="wrapper">
<ui-gmap-polyline ng-repeat="p in polylines" path="p.path" stroke="p.stroke" visible='p.visible' geodesic='p.geodesic' fit="false"
editable="p.editable" draggable="p.draggable" icons='p.icons'></ui-gmap-polyline>
</ui-gmap-google-map>
<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.1/lodash.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="http://cdn.rawgit.com/nmccready/angular-simple-logger/0.0.1/dist/index.js"></script>
<script src="http://cdn.rawgit.com/angular-ui/angular-google-maps/master/dist/angular-google-maps.min.js"></script>
</div>

Refreshing map and markers with angular-google-maps

Hi I am using the angular-google-maps for my project. The html and js code is as follows
html:
<ui-gmap-markers models="apartments" coords="'loc'" icon="'assets/images/map_icon_normal.png'" idkey="'_id'"
fit="'false'" click="click">
<ui-gmap-windows show="'show'" >
<div ng-non-bindable>{{streetAddress}}</div>
</ui-gmap-windows>
</ui-gmap-markers>
</ui-gmap-google-map>
Script:
angular.module('myApp')
.controller('MapCtrl',
function ($scope, $routeParams, Map, uiGmapGoogleMapApi) {
$scope.apartments = [];
$scope.customIcon = "../../assets/images/map_icon_normal.png"
$scope.map = {
center: {
latitude: $routeParams.lat,
longitude: $routeParams.lon
},
zoom: 5,
bounds: {},
events: {
tilesloaded: function (map) {
//console.log('tiles loaded');
$scope.$apply(function () {
$scope.mapInstance = map;
//console.log(map.getBounds().getNorthEast());
$scope.searchbox.options.bounds = new google.maps.LatLngBounds($scope.mapInstance.getBounds().getNorthEast(),
$scope.mapInstance.getBounds().getSouthWest());
});
},
idle: function(map) {
$scope.map.refresh = false;
},
resize: function(map) {
console.log('resize');
},
dragend: function() {
}
},
markersEvents: {
click: function(marker, eventName, model, args) {
console.log('markerEvent click');
$scope.map.window.model = model;
$scope.map.window.show = true;
}
},
window : {
marker: {},
show: false,
closeClick: function() {
this.show = false;
},
options: {} // define when map is ready
},
control: {},
refresh: function () {
$scope.map.control.refresh();
}
}
uiGmapGoogleMapApi.then(function (map) {
$scope.getData(20, 0, map);
map.visualRefresh = true;
$scope.mapInstance = map;
})
$scope.getData = function(limit, offset, map) {
Map.getApartments($routeParams.lat, $routeParams.lon, limit, offset).success(function (data) {
///----- I get undefined error here---
$scope.map.control.refresh();
});
}})
}
I am not sure how to refresh the map with the new markers or even trigger an update to the map. I played around with 'control' and 'refresh' params of the ui-gmap-google-map but cannot get it to work.
You need to use uiGmapIsReady --- not uiGmapGoogleMapApi --- to wait for control objects to be augmented with their methods (such as refresh).
The uiGmapIsReady service provides a promise which resolves when all uiGmapGoogleMap directives have been fully initialized, while the uiGmapGoogleMapApi service resolves simply when the Google Maps JS API has loaded.
See this answer for an example of using uiGmapIsReady. And of course, don't forget the docs.
Regarding how to get updates to your models property on the scope to cause updates to your map, your code example needs to be fleshed out and cleaned up to help you there. (For example, what is the resolution of getApartments doing to update $scope.apartments? Or maybe asking that question is itself the answer?) Take a look at this fiddle, it might help you in the meantime.
Try dorebuildall attribute.
<ui-gmap-markers
models="apartments"
coords="'loc'"
icon="'assets/images/map_icon_normal.png'"
idkey="'_id'"
fit="'false'"
click="click"
dorebuildall="true">
<ui-gmap-windows></ui-gmap-windows>
</ui-gmap-markers>
More details at: http://angular-ui.github.io/angular-google-maps/

Can't remove markers with AngularJS Google Maps plugin and Ionic

my html page renders the map by this:
<ui-gmap-google-map center='map.center' zoom='map.zoom'>
<ui-gmap-markers models="markers" coords="'coords'" icon="'icon'" ></ui-gmap-markers>
</ui-gmap-google-map>
And this is the controller:
angular.module('controllers.mapscontroller', [])
.controller("MapCtrl", function($scope, uiGmapGoogleMapApi, dataFactory) {
$scope.POIs=[];
$scope.markers = [];
uiGmapGoogleMapApi.then(function(maps) {
$scope.map = { center: { latitude: 40.3555013, longitude: 18.1573811 }, zoom: 8 };
navigator.geolocation.getCurrentPosition(function (position) {
$scope.map = { center: { latitude: position.coords.latitude, longitude: position.coords.longitude }, zoom: 8 };
});
dataFactory.getPOIs("it-IT")
.success(function (data) {
$scope.POIs=data.data.contents;
$scope.initializePOIsOnMap();
})
.error(function (error) {
console.log(error);
});
});
$scope.removePOIs = function() {
$scope.markers=[]; //<-- does nothing !!!
};
$scope.initializePOIsOnMap = function() {
for(var POI in $scope.POIs) {
var marker = {
id: $scope.POIs[POI].id,
coords: {
latitude: $scope.POIs[POI].latitude,
longitude: $scope.POIs[POI].longitude
},
options: { draggable: false , visible:true},
icon: "img/catIcons/"+$scope.POIs[POI].catid+".png"
};
$scope.markers.push(marker);
}
}
});
Maps gets displayed correctly, and markers as well.
But unfortunately, as you can read in $scope.removePOIs function, I can't remove the markers from the map. I've tried different solutions found over stackoverflow and the Web ($scope.markers.length=0, marker.setMap(null), ...) but no luck.
Any hint??
Thanks
Roberto
Solved!!
The problem was that I specified the controller twice: in the app.js and in the HTML page. The reason for specifying it in the HTML page is that I use the switchery plugin, which requires the ng-controller attribute to be set in the tag.
I removed the controller property from the app.js, putted all the HTML (the maps tags) within the tag and now it works.
Thanks!
Roberto
Here's an example of deleting markers using angularjs:
Example
Look at the script for remove markers example.

How do I add markers to a Google Map?

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
}
}
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

Resources