Ionic map controller not getting loaded - javascript

I have a 5 tab's app one of which contains a map.The map loads only when browsed to directly in the url bar.Otherwise it seems the controller is not loaded as i determined by some console logs. as the app will be run on mobile devices the map page will never be loaded first so i need a fix for this. I thought the controllers would be called when a tab is clicked but that doesn't seem t be the case.
Controller
.controller('MapCtrl', function($scope, $ionicLoading, $compile) {
//console.log("Map controller");
function initialize() {
var myLatlng = new google.maps.LatLng(43.07493,-89.381388);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//console.log('placing map');
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
//Marker + infowindow + angularjs compiled ng-click
var contentString = "<div><a ng-click='clickTest()'>Click me!</a></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Uluru (Ayers Rock)'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
$scope.map = map;
}
google.maps.event.addDomListener(window, 'load', initialize);
$scope.centerOnMe = function() {
if(!$scope.map) {
return;
}
$scope.loading = $ionicLoading.show({
content: 'Getting current location...',
showBackdrop: false
});
navigator.geolocation.getCurrentPosition(function(pos) {
$scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
$scope.loading.hide();
}, function(error) {
alert('Unable to get location: ' + error.message);
});
};
$scope.clickTest = function() {
alert('Example of infowindow with ng-click')
};
})
View
<ion-view view-title="Directions">
<ion-content>
<div id="map" class="card" data-tap-disabled="true">
</div>
</ion-content>
</ion-view>
Tabs
<ion-tab title="Directions" icon-off="ion-ios-location-outline" icon-on="ion-ios-location" href="#/tab/directions">
<ion-nav-view name="tab-directions"></ion-nav-view>
</ion-tab>
Router
.state('tab.directions', {
url: '/directions',
views: {
'tab-directions': {
templateUrl: 'templates/tab-directions.html',
controller: 'MapCtrl'
}
}
})
please ask questions it there is more info i can give you.

I had the same issue. I execute the function when the view is entered.
I added google.maps.event.trigger( map, 'resize' ); after $scope.map = map; because the map only loaded after refreshing the view.
This is my controller:
.controller('MapsController', function($scope, $ionicLoading){
$scope.$on( "$ionicView.enter", function( scopes, states ) {
var myLatlng = new google.maps.LatLng(37.3000, -120.4833);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
navigator.geolocation.getCurrentPosition(function (pos) {
map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: map,
title: "My Location"
});
});
$scope.map = map;
google.maps.event.trigger( map, 'resize' );
});
});

Related

Google map Blue-Dot for current location in reactjs

I was implementing google maps..And i want the default google blue dot for the current location. can anyone please tell, how to do so, in reactjs or in simple javascript..
First you have to allow the browser to send your Geo location to Google API, then wire up this code on the window/document load event :
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
var marker = new google.maps.Marker({
position: pos,
map: map,
title: 'Hello World!',
icon: 'https://maps.google.com/mapfiles/kml/shapes/info-i_maps.png',
});
map.setCenter(pos);
}, function () {
//handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
//handleLocationError(false, infoWindow, map.getCenter());
}
}

ERROR TypeError: Cannot read property '__e3_' of undefined

I'm developing a web app with angular 6. I integrated google maps but marker click event is returning me an error.
Help me, thanks in advance.
import { } from '#types/googlemaps';
#ViewChild('whereMap') gmapElement: any;
map: google.maps.Map;
marker: google.maps.Marker;
initMapp() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
let location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.map = new google.maps.Map(this.gmapElement.nativeElement, {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
let marker = new google.maps.Marker({
position: location,
map: this.map,
draggable: true,
animation: google.maps.Animation.DROP,
title: 'Got you!'
});
});
google.maps.event.addListener(this.marker, 'click', () => {
console.log('marker clicked');
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
}
map initialized and marker is working fine, but im unable to fire click event.
i have called the initMapp() in ngOnInit().
The navigator.geolocation.getCurrentPosition is asynchronous, you are likely meeting a race condition. You should move google.maps.event.addListener inside geolocation callback, otherwise you can try to assign event listener before the marker element was created.
Google Maps JavaScript API error message ERROR TypeError: Cannot read property '__e3_' of undefined typically means that you try to assign event to non-existing DOM element.
Try the following
initMapp() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
let location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.map = new google.maps.Map(this.gmapElement.nativeElement, {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
this.marker = new google.maps.Marker({
position: location,
map: this.map,
draggable: true,
animation: google.maps.Animation.DROP,
title: 'Got you!'
});
google.maps.event.addListener(this.marker, 'click', () => {
console.log('marker clicked');
});
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
I hope this helps!

Marker does not show up on map angularjs

I am using angular-maps to create a map, with a list of markers.
I have a problem displaying the markers. I have no errors though.
Here is my code:
Controller
var app = angular.module('mapController', []);
app.service('Map', function($q) {
this.init = function() {
var options = {
center: new google.maps.LatLng(45.7154289, 4.9317724),
zoom: 14,
disableDefaultUI: true
}
this.map = new google.maps.Map(
document.getElementById("map"), options
);
this.places = new google.maps.places.PlacesService(this.map);
var markers = [{
"title": 'Capgemini',
"lat": '45.7154289',
"lng": '4.9317724',
"description": 'Capgemini'
}];
var defaultMarkerColor = 'ff0000';
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + defaultMarkerColor);
// marker object for the marker
var marker = new google.maps.Marker({
position: google.maps.LatLng(markers[0].lat,markers[0].lng),
map: this.map,
title: markers[0].title,
animation: google.maps.Animation.DROP,
icon: pinImage
});
}
this.search = function(str) {
var d = $q.defer();
this.places.textSearch({query: str}, function(results, status) {
if (status == 'OK') {
d.resolve(results[0]);
}
else d.reject(status);
});
return d.promise;
}
this.addMarker = function(res) {
if(this.marker) this.marker.setMap(null);
this.marker = new google.maps.Marker({
map: this.map,
position: res.geometry.location,
animation: google.maps.Animation.DROP
});
this.map.setCenter(res.geometry.location);
}
});
app.controller('mapController', function($scope, Map) {
$scope.place = {};
$scope.search = function() {
$scope.apiError = false;
Map.search($scope.searchPlace)
.then(
function(res) { // success
Map.addMarker(res);
$scope.place.name = res.name;
$scope.place.lat = res.geometry.location.lat();
$scope.place.lng = res.geometry.location.lng();
},
function(status) { // error
$scope.apiError = true;
$scope.apiStatus = status;
}
);
}
$scope.send = function() {
alert($scope.place.name + ' : ' + $scope.place.lat + ', ' + $scope.place.lng);
}
Map.init();
});
and the HTML :
<ion-content ng-controller="mapController" style="margin-top: 25px">
<div class="container">
<div id="map" libraries="places" data-tap-disabled="true"></div>
<form name="searchForm" novalidate
ng-submit="search()">
<div class="input-group">
<input name="place" type="text" class="form-control"
ng-model="searchPlace" required autofocus />
<br>
<span class="input-group-btn">
<button class="btn btn-primary"
ng-disabled="searchForm.$invalid">Search</button>
</span>
</div>
</form>
</div>
The map shows up correctly, and centered on the coordinates I chose, but without a marker.
I would appreciate any help.
Hi took me sometime to put in place the fiddle... :)
I made this changes to make it work:
The markers:
var markers = [{
"title": 'Capgemini',
"lat": 45.7154289,
"lng": 4.9317724,
"description": 'Capgemini'
}];
And then the marker definition
var marker = new google.maps.Marker({
position:{lat: markers[0].lat, lng: markers[0].lng},
map: this.map,
title: markers[0].title,
animation: google.maps.Animation.DROP,
icon: pinImage
});
the easiest way is to use numbers for the coords.
here you can find the fiddle
it isn't super clean and it is lot of debug stuff and most important if you can initialize and see the map you don't really need it.
hope this help

When clicking cluster, how to show Infowindow which has markers's values?

I have been trying to use google map with angularJS.
I have learned how to use it through https://angular-ui.github.io/angular-google-maps/#!/.
Everything goes well.
For each marker, I can show InfoWindow which has an element information of myList.
But I have got stuck in InfoWindow with cluster.
When cluster is clicked, I want to show the information list of markers in cluster.
Even I can't show simple InforWindow when clicking the cluster.
Below sources are my code.
Please tell me if it is not enough to solve my problem.
Please tell me what is wrong and how to solve this.
Have a nice day.
* javascript
$scope.map.map = {
center: { latitude: $scope.map.myList[0].lat, longitude: $scope.map.myList[0].lng },
zoom: 17,
events : {
tilesloaded: function (map) {
$scope.$apply(function () {
google.maps.event.addDomListener(window, 'resize', function() {
var lat = $scope.map.myList[$scope.map.markerPosition-1].lat;
var lng = $scope.map.myList[$scope.map.markerPosition-1].lng;
var center = new google.maps.LatLng(lat, lng);
map.setCenter(center);
});
});
}
},
markersEvents: {
click: function(marker, eventName, model) {
model.show = !model.show;
return;
}
},
clusterOptions : { // options of cluster
gridSize: 40,
ignoreHidden: true,
zoomOnClick : false,
averageCenter : true,
styles: [
{
height: 53,
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m3.png",
width: 53,
textColor : 'white'
}
]
},
clusterEvent: { // when cluster's clicked
click: function(map, markers) {
var contentString = 'ABCD';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
infowindow.open(map, markers);
return;
}
}
};
$scope.map.options = {
streetViewControl : false
};
$scope.map.markers = [];
* html
<ui-gmap-google-map center='map.map.center' zoom="map.map.zoom" options="map.options" events="map.map.events">
<ui-gmap-markers models="map.markers" coords="'self'" icon="a" events="map.map.markersEvents" options="'options'"
doCluster="true" clusterOptions="map.map.clusterOptions" clusterEvents="map.map.clusterEvent">
<ui-gmap-windows show="show">
<div ng-non-bindable>{{id}}</div>
</ui-gmap-windows>
</ui-gmap-markers>
Answer myself.
var infoWindowOptions = {
content: "asdfasdf"
};
var infowindow = new google.maps.InfoWindow(infoWindowOptions);
infowindow.open(map.map_, *marker*);

change google map with changing city name in dropdown list

I have included the city specific latitude, longitude in a city.js file and i am getting the content of the city from that file.
Now, i want to pass that information into my javaScript code to change the map with the change in city name.
I have tried something like this but didn't get success-----
$(document).ready(function()
{
$.get('City.js', function(data){
var jsonObject = JSON.parse(data);
var lat = jsonObject[1].latitude;
var lng = jsonObject[1].longitude;
var latlng = new google.maps.LatLng(lat, lng);
$("#City").change(function () {
var marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: true
});
});
});
here city.js is a java script file.The content of the java script file is---
var jsonObject = [{ "CityId": "1", "CityName": "Faridabaad", "latitude": "28.4211", "longitude": "77.3078" },
{ "CityId": "2", "CityName": "Greater Noida", "latitude": "28.4962", "longitude": "77.5360" }];
My dropdown list which changes locality name as the city name changes is working fine.Now, i only want is to change google map as the city name changes in the dropdown list----My working code is like this----
$("#City").change(function () {
$("#Locality").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("LoadLocalities","Project")',
dataType: 'json',
data: { id: $("#City").val() },
success: function (localities) {
$.each(localities, function (i, locality) {
$("#Locality").append('<option value="' + locality.Value + '">' +
locality.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retreive Locality.' + ex);
}
});
return false;
})
});
My javaScript code for loading google map is as----
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(28.713956, 77.006653);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
draggable: true,
animation:google.maps.Animation.BOUNCE,
position: myLatlng,
map: map,
title: "Project location"
});
google.maps.event.addListener(marker, 'dragend', function (event) {
//document.getElementById("lat").value = event.latLng.lat();
//document.getElementById("long").value = event.latLng.lng();
document.getElementById("Geolongitude").value = event.latLng.lng();
document.getElementById("Geolatitude").value = event.latLng.lat();
});
google.maps.event.addListener(marker, 'click', function () {
map.setZoom(9);
map.setCenter(marker.getPosition());
});
}
google.maps.event.addDomListener(window, "load", initialize);
My form are having two dropdown list like this---
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Enter the Project Details</legend>
<div class="editor-label">
#Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
#if (ViewData.ContainsKey("City")){
#Html.DropDownListFor(model => model.City, ViewData["City"] as List<SelectListItem>, new { style = "width:250px", #class = "DropDown1"}) #Html.ValidationMessageFor(model => model.City)
}
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Locality)
</div>
<div class="editor-field">
#Html.DropDownList("Locality", new SelectList(string.Empty,"Value","Text"),"Please Select a locality", new { style = "width:250px", #class = "DropDown1" })
If you want set the map center do it;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-27.793949,-52.348643),
mapTypeId: google.maps.MapTypeId.ROADMAP };
// Save map as global variable.
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
On your change City function;
// Catch center;
center = map.getCenter();
// .. insert your code here to change center object lat/long
// center.lat = -50.00 ( I do not remember the atribute name )
map.setCenter(center);

Categories