Markers not loading in Google Maps - angularjs

I am able to load markers from a local database I include in my Ionic app that is just a simple array of lat/lon coords. The trouble is when I try and load them from a JSON file on the web. Any help would be appreciated. Thanks!
this is the call I use:
get('assets/data/markers.json')
And that all works fine for populating the map from a local data file.
Now my issue is that I would like to display markers from a JSON file that is located at :
http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500
Although when I change the get request to include that link as such:
get('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500')
It gives me the following error message:
I believe I am not parsing the coords correctly in my marker function, yet I am unsure how to do this with the JSON array. Here is a visual of what the location structure looks like in the file:
My home.ts marker map/marker functionality:
displayGoogleMap(){
let latLng = new google.maps.LatLng(43.653908,-79.384293);
let mapOptions = {
center:latLng,
zoom:12,
mapTypeId : google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}
getMarkers(){
//this.http.get('assets/data/markers.json').map((res)=>res.json()).subscribe(data=>{
this.http.get('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR? limit=500').map((res)=>res.json()).subscribe(data=>{
this.addMarkersMap(data);
});
}
addMarkersMap(markers){
for(let marker of markers){
var loc = {lat: marker.latitude , lon: marker.longitude};
console.log(loc);
marker = new google.maps.Marker({
position: loc,
map: this.map,
//title:marker.name,
//label:marker.content
});
}

You are accessing non-existing key from marker object. Try to change below function.
addMarkersMap(markers)
{
for(let marker of markers)
{
var loc = {lat: marker.calEvent.locations[0]['coords'].lat , lon: lat: marker.calEvent.locations[0]['coords'].lng};
console.log(loc);
marker = new google.maps.Marker({
position: loc,
map: this.map
});
}
}

Related

Cannot find a differ supporting object '33.265625' of type 'number'

I have a Ionic App using google maps. I am trying to get latitude and longitude from data json api for flight route and that data json api then inject that data to Google Maps polyline . Fetch data json api working fine without problem , but when l put objects inside Google Maps l get error Error: Cannot find a differ supporting object '33.265625' of type 'number'. NgFor only supports binding to Iterables such as Arrays. l use forEach to move through the array .
my code :
async getmarker(){
this.http.get('/v1/flightjson?flightId=201',{},{})
.then( data=>{
// this.latitude = JSON.parse(data.data).result.response.data.flight.track.latitude
// this.longitude = JSON.parse(data.data).result.response.data.flight.track
for(let datas of JSON.parse(data.data).result.response.data.flight['track']) {
this.longitude = datas.longitude
this.latitude = datas.latitude
console.log(this.longitude)
// Do something.
}
})
}
loadMap() {
let AIR_PORTS = [
this.latitude,
this.longitude
];
this.map = GoogleMaps.create('map_canvas');
let polyline: Polyline = this.map.addPolylineSync({
points: AIR_PORTS,
color: '#AA00FF',
width: 10,
geodesic: true,
clickable: true // clickable = false in default
});
polyline.on(GoogleMapsEvent.POLYLINE_CLICK).subscribe((params: any) => {
let position: LatLng = <LatLng>params[0];
let marker: Marker = this.map.addMarkerSync({
position: position,
title: position.toUrlValue(),
disableAutoPan: true
});
marker.showInfoWindow();
});
}
my data json url
html
<div id="map_canvas"></div>
for(let datas of JSON.parse(data.data).result.response.data.flight['track']) {
this.longitude = datas.longitude
this.latitude = datas.latitude
}
In above for loop, I assume this.longitude and this.latitude will be arrays.
You should push elements inside this.longitude and this.latitude (as shown below), instead of replacing previous value.
this.longitude.push(datas.longitude);
this.latitude.push(datas.latitude);
You may be using these variables to iterate through different points on the map, as they are plain numbers, ngFor will throw an error saying that content inside ngFor should be iterable.
Array is an iterable whereas number is not.

ng-click in a loop is always clicked - ionic 2

I have a google map in my view and in this map I have many marker and each marker should have a content which contains an a href for more details
This is my code for adding one marker which is used in a loop on all the events saved in the database :
setMarker(event){
let coords = event.location.split(",");
let location = new google.maps.LatLng(coords[0],coords[1]);
let marker = new google.maps.Marker({
map: this.map,
position: location
});
let content = "<h1>" + event.name + "</h1></br><a ng-click="+this.viewEventDetails(event)+"> More Details</a>";
let infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
return marker;
}
and this is my viewEventDetails function :
viewEventDetails(event){
this.navCtrl.push(EventDetailsPage, event);
}
When I load the map view it loads the viewEventDetails on all events , what should I do please ?
Could you change "</h1></br><a ng-click="+this.viewEventDetails(event)+"> More Details</a>" to "</h1></br><a ng-click=\"viewEventDetails(event)\"> More Details</a>". I think this should work.
Btw I think ng-click should also be substitude with (click) since ionic 2 does the angular2 way and therefore does not accept ng-click.

Angular Google Maps - automatically set 'center' and 'zoom' to fit in all markers

I have a dynamically generated list of markers within my Google Map. I want the map's center to be the center of all the markers and zoomed out just enough so that all markers are in view.
In terms of calculating the map center, perhaps this could be possible by iterating through all the latitudes and longitudes and finding the central point. However, I cannot figure out the best way to calculate what the zoom should be.
Is this possible to achieve?
My map is being used in the template like this:
<ui-gmap-google-map events="map.events" center="map.center" zoom="map.zoom" draggable="true" options="options">
<ui-gmap-marker ng-repeat="home in filteredHomes = (resCtrl.filteredHomes | orderBy : $storage.params.orderby : $storage.params.reverseOrder)" coords="{latitude: home.location.latitude, longitude: home.location.longitude}" idkey="home.homeId">
</ui-gmap-marker>
</ui-gmap-google-map>
UPDATE
Attempted Angular implementation from advice from #Tiborg:
uiGmapGoogleMapApi.then(function(maps) {
$scope.map = {
center: $scope.$storage.params.views.map.location,
zoom: $scope.$storage.params.views.map.zoom,
events: {
click: function() {
var bounds = new google.maps.LatLngBounds();
for (var i in $scope.filteredHomes) {
bounds.extend($scope.filteredHomes[i].location);
}
$scope.map.fitBounds(bounds);
}
}
};
});
This produces the console error: TypeError: undefined is not a function (evaluating 'a.lat()')
Use the LatLngBounds class in Google Maps API, like this:
var bounds = new google.maps.LatLngBounds();
for (var i in markers) // your marker list here
bounds.extend(markers[i].position) // your marker position, must be a LatLng instance
map.fitBounds(bounds); // map should be your map class
It will nicely zoom and center the map to fit all your markers.
Of course, this is the pure javascript, not the angular version, so if you have problems implementing it in angular (or you don't have access to the map instance from where you get the markers), let me know.
angular-google-maps has taken care of this feature. All you need to do is add fit="true" attribute in your markers directive (ui-gmap-markers).
Example : <ui-gmap-markers models="map.markers" fit="true" icon="'icon'">
Please refer the document http://angular-ui.github.io/angular-google-maps/#!/api
The answer has been posted for another problem: https://stackoverflow.com/a/23690559/5095063
After that you have just to add this line:
$scope.map.control.getGMap().fitBounds(bounds);
Thanks to all the replies, I got this code which is working perfectly for me:
var bounds = new google.maps.LatLngBounds();
for (var i = 0, length = $scope.map.markers.length; i < length; i++) {
var marker = $scope.map.markers[i];
bounds.extend(new google.maps.LatLng(marker.latitude, marker.longitude));
}
$scope.map.control.getGMap().fitBounds(bounds);
I hope it will help to someone.
Also use timeout to make sure it is digested properly
uiGmapIsReady.promise()
.then(function (map_instances) {
var bounds = new google.maps.LatLngBounds();
for (var i in $scope.map.markers) {
var marker = $scope.map.markers[i];
bounds.extend(new google.maps.LatLng(marker.latitude, marker.longitude));
}
$timeout(function() {
map_instances[0].map.fitBounds(bounds);
}, 100);
});

AngularJS and google-maps

I'm using Google Maps for AngularJS to add a map to my project in AngularJS. Everything works great, except the case when at certain point I want the map center to be the exactly the same position as the clicked marker. So, on a click event I set the center of the map in AngularJS controller. Everything is OK, but when I drag or zoom the map, the marker position becomes the "new" center of the map. Does anybody know why is this happening? It's like the marker coords are binded in bi-directional way... Any help is appreciated! Thanks in advance
Here's the code:
// angular js controller
// map init [displays markers for all railway terminals in DB]
$scope.map = {
center: {
latitude: 48.22476,
longitude: 16.41356
},
zoom: 4
};
$scope.markers = []; // later filled with data from DB
// some code in between ...
// selection in table with termnals
$scope.selectTerminal = function (terminal) {
$scope.selected.terminal = terminal;
if (terminal.placeId != $scope.currentSelectedId) {
$scope.currentSelectedId = $scope.selected.terminal.placeId;
$scope.getTerminalDetails($scope.selected.terminal.placeId);
$scope.map.center = terminal.address.coords; // THIS LINE GIVES ME TROUBLE
$scope.map.zoom = 12;
}
};
So, the map center is set according to the coordinates of the selected terminal on select action (it is the new center of the map), and the zoom level increases. The thing is when i try to reset the map, or try to zoom or drag the map, the marker coordinates get the new map center coords, but it shouldn't. That's why I say 'two-way binding', I just can't figure this thing out.
Using your example you can do this.
$scope.map = {
center: {
latitude: 48.22476,
longitude: 16.41356
},
zoom: 4,
markersEvents: {
click: function(marker, eventName, terminal) {
$scope.map.center.latitude = terminal.coords.latitude;
$scope.map.center.longitude = terminal.coords.longitude;
}
}
};
remember in the html marker introduce events="map.markersEvents"

Google Map API v3, changing map type by clicking the link: "map is not defined"

I'm using simpliest example from the official documentation:
function initialize() {
var mapCent = new google.maps.LatLng($shirota, $dolgota);
var myOptions = {
zoom: $uvelichenie,
center: mapCent,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(
document.getElementById("map_canvas"),
myOptions);
}
I've added this to change map type dynamically as described in the official documentation:
function perekluchitDor() {
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
}
This into a href in HTML part:
onclick="perekluchitDor();">
Everything is pretty simple, but still doesn't work. All that I can see is the error "map is not defined" when I click the link.
I wonder what am I doing wrong here?
This is a variable scope issue. You need to declare map outside of your functions, as below (1st line of code).
var map;
function initialize() {
var mapCent = new google.maps.LatLng($shirota, $dolgota);
var myOptions = {
zoom: $uvelichenie,
center: mapCent,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(
document.getElementById("map_canvas"),
myOptions);
}
var name1 = "value";
name1 = "value";
Used outside of a user-defined function, both of these do exactly the same. Both
create a global variable. A global variable can be accessed from any function in any
window or frame that is currently loaded. If we use var name1 inside a user-defined
function it is local in scope, we only can see it inside the function.
You need to only remove var, behined from map statement. You don't need to declare map outside of your functions.

Resources