I have a backbone.js model. I want to load google maps API javascript from that model's method. I don't want to load the script in head of the document.
I can use $.getScript() to load the js & then display the map? But when I specify the callback function
http://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=TRUE&callback=initialize
I always get an error because I dont want to define a global js function initialize(). I want the callback method to be a same backbone.js model's method.
App = Backbone.Model.extend({
construct : function(),
displayMap : function()
{
$.getScript("http://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=TRU&callback=initialize", function(data, textStatus, jqxhr) {
console.log('Load was performed.');
});
},
initialize: function()
{
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
});
var App = new App();
App.displayMap();
Try this structure for map model:
Map = Backbone.Model.extend({
defaults: {
id: '', currentLatLng: {}, mapOptions: {}, map: {},
position: {}, zoom: 13, maxZoom: 16, minZoom: 12
},
initMap: function(position){
this.set('position', position);
var currentLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.set('currentLatLng', currentLatLng);
var mapOptions = {
zoom: this.get('zoom'),
minZoom: this.get('minZoom'),
maxZoom: this.get('maxZoom'),
center: currentLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
this.set('mapOptions', mapOptions);
}
});
This code for view:
MapView = Backbone.View.extend({
defaults:{
region: 'us', language: 'en'
},
id: 'gmaps-container',
className: 'gmaps_container',
initialize: function(){
var url = "http://maps.googleapis.com/maps/api/js?key=key_here&sensor=false";
$.ajax({
url: url,
dataType: "script",
async: false,
success: function(){
console.log('script loaded');
}
});
this.model.set('map', new google.maps.Map(this.el, this.model.get('mapOptions')));
},
render: function(){
console.log('init map');
$('#' + this.id).replaceWith(this.el);
return this;
}
});
And just initialize model and view in main script:
var map = new Map({zoom: 8, maxZoom: 18, minZoom: 8});
map.initMap({coords: {latitude: -34.397, longitude: 150.644}});
var mapView = new MapView({model: map});
mapView.render();
Also you need simple html container:
<div id="gmaps-container" class="gmaps_container"></div>
Note: set width and height for container.
Related
I created a map with Google maps. At first the infowindow is open when the init function is called. I select a place from the map $scope.kds is working and the contents of the infowindow change. There is a button in the infowindow. When I click the button doesnt work. How can I do?
window.ngApp = angular.module('test', []);
window.ngApp.controller('controllerMap', ['$scope', '$location', '$compile', function ($scope, $location, $compile) {
$scope.init = function () {
$scope.latlng = new google.maps.LatLng($scope.lat, $scope.lng);
$scope.map = new google.maps.Map(document.getElementById('map'), {
center: $scope.latlng,
zoom: $scope.zoom,
minZoom: 6,
maxZoom: 21
});
$scope.marker = new google.maps.Marker({
map: $scope.map,
position: $scope.latlng,
draggable: true,
icon: 'static/img/pin-4ldpi.png'
});
$scope.infowindow = new google.maps.InfoWindow({
content: "",
maxWidth: 175
});
google.maps.event.addListener($scope.map, 'click', function (event) {
$scope.kds ();
});
$scope.kds = function(){
$.ajax({
type: 'post',
url: "/",
dataType: 'json',
async: true,
cache: false,
data: {
mode: "getkds",
lat: data.response.lat,
lng: data.response.lng
},
success: function (data) {
if (data.response) {
$scope.cityName = data.response.cityName;
$scope.contentString = "<div class='text-center fs-16 py-3'>" + $scope.cityName + " <br>\n" +
"<a ng-click='runfunc();' class='fs-12 text-red font-sfprodisplay-600 btn btn-color3 btn-sm mt-3'>Analyses</a></div>";
$scope.infowindow.setContent($scope.contentString);
$scope.infowindow.open($scope.map, $scope.marker);
if (!$scope.$$phase) $scope.$apply();
}
}
});
}
$scope.runfunc=function(){
alert("123");
}
$scope.init();
}]);
I am working on an ionic app in which i need to show google map to display location. I need to disable the satellite and street view options in the map, but didnt get any suitable method.
Also the map is creating issues, sometimes it shows on the screen and sometime it didnt.
This is the code i am trying in controller
$scope.addLoc = function(){
$cordovaGeolocation.getCurrentPosition(options).then(function(position){
$scope.lat = position.coords.latitude;
$scope.long = position.coords.longitude;
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+$scope.lat+","+$scope.long+"&sensor=true";
$http.get(url)
.then(function(res) {
$rootScope.address = res.data.results[0].formatted_address;
console.log($rootScope.address);
}, function(error) {
console.log( error);
});
console.log(position);
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.marker = new google.maps.Marker({
position: new google.maps.LatLng($scope.lat, $scope.long),
map: $scope.map,
title: 'Drag me!'
}, function(err) {
console.err(err);
});
}, function(error){
console.log("Could not get location");
});
}
You can try this
var mapOptions = {
center: latLng,
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
disableDefaultUI: true
};
Doc: https://developers.google.com/maps/documentation/javascript/controls#DefaultUI
When you enable the map and passes the options to it, you have the chance to specify a mapTypeControlOptions. These have an Array that specifies what kind of maptype's you will allow the user to be able to see. It can be seen here http://code.google.com/apis/maps/documentation/javascript/reference.html#MapTypeControlOptions.
If you don't want the user to have any options as to the maptypes, you can also specify that by setting the maps mapTypeControl to false.
var myOptions = {
zoom: 2,
center: **Your LatLng object**,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID]
}, // hereĀ“s the array of controls
disableDefaultUI: true, // a way to quickly hide all controls
mapTypeControl: true,
scaleControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); // displays in <article id="map_canvas"></article>
//map.mapTypeControl = false; // OPTIONAL: hides the map control
You can hide them via css
But this not a proper way..This may not work in the future..
.gm-style-mtc {
display: none;
}
I am trying to get coordinates while tap or hold events in ionic from the Google Maps.
While holding I am getting values in browser console not getting in device.
How to clear this issue?. I need to get values while holding/taping in mobile apps using ionic framework [google maps].
Any help would be appreciated.Thanks in advance.
.controller('HomeCtrl', function ($scope, $rootScope, $cordovaGeolocation, $ionicLoading, $ionicGesture) {
$ionicLoading.show({
template: '<ion-spinner icon="bubbles"></ion-spinner><br/>Acquiring location!'
});
var posOptions = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 0
};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
$rootScope.currentlat = lat;
$rootScope.currentlong = long;
var myLatlng = new google.maps.LatLng(lat, long);
$rootScope.myLatlng = myLatlng;
var mapOptions = {
center: myLatlng,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.map = map;
marker = new google.maps.Marker({
position: myLatlng,
map: $scope.map
});
var element = angular.element(document.querySelector('#map'));
$ionicGesture.on('hold', function(e){
$scope.$apply(function() {
alert('hold happens');
google.maps.event.clearListeners(map, 'click');
google.maps.event.addListener(map, 'click', function(event) {
alert(event.latLng);
});
});
}, element);
google.maps.event.addListener(marker, "click", function (event) {
});
$ionicLoading.hide();
}, function (err) {
$ionicLoading.hide();
console.log(err);
});
}
I think your problem is that your using
$ionicGesture.on('hold')
Iconic uses Cordova and Cordova google maps has its own event handler as the "map" is in native view not JavaScript related. You can read up in more detail here.
So once your device is ready
var map = new google.maps.Map(document.getElementById("map"), mapOptions),
longClick = plugin.google.maps.event.MAP_LONG_CLICK;
map.on(longClick, function (latLng) {
var selectedLatLocation = latLng.lat.toString();
var selectedLongLocation = latLng.lng.toString();
alert(selectedLatLocation, selectedLongLocation);
});
We are trying to using this Codepen within our latest Ionic Framework/AngularJS project and can't seem to figure this issue out.
We want to be able to click 'Find Us' and have the Google Map Marker display our current location.
If anyone can see where we're going wrong please let us know.
Thank you.
// Google Map
.controller('MapCtrl', function($scope, $ionicLoading, $compile) {
function initialise() {
var myLatlng = new google.maps.LatLng(53.068165,-4.076803);
var mapOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
});
$scope.map = map;
}
google.maps.event.addDomListener(window, 'load', initialise);
$scope.centerOnMe = function() {
if(!$scope.map) {
return;
}
$scope.loading = $ionicLoading.show({
showBackdrop: true
});
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);
});
};
});
Here's a good example of this.
Codepen link
.controller('MarkerRemoveCtrl', function($scope, $ionicLoading) {
$scope.positions = [{
lat: 43.07493,
lng: -89.381388
}];
$scope.$on('mapInitialized', function(event, map) {
$scope.map = map;
});
$scope.centerOnMe= function(){
$ionicLoading.show({
template: 'Loading...'
});
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
$scope.positions.push({lat: pos.k,lng: pos.B});
console.log(pos);
$scope.map.setCenter(pos);
$ionicLoading.hide();
});
};
});
I did use a directive for google maps, just to keep everything in angular-land.
Here is a CodePen of an Ionic app with Google Maps
angular.module('ionic.example', ['ionic'])
.controller('MapCtrl', function($scope, $ionicLoading, $compile) {
function initialize() {
var myLatlng = new google.maps.LatLng(43.07493,-89.381388);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
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')
};
});
when you find the current location of your phone first you find out the latitude and longitude.So First,Add the plugin your project
1.cordova plugin add cordova-plugin-geolocation
2.module.controller('GeoCtrl', function($cordovaGeolocation,$http) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude //here you get latitude
var long = position.coords.longitude //here you get the longitude
$http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=true').then(function(data){ $rootScope.CurrentLocation=data.data.results[0].formatted_address;//you get the current location here
}, function(err) {
// error
});
}, function(err) {
// error
});
}):
I'am a new Backbone user and started to implement Google Maps in it. I set this up in de View object. I works all fine, but when i go to another page (template with the navigator object) and go back to the page with Google Maps, the current position dont market on the Google Map.
Below my code from my View
DFM.MapView = Backbone.View.extend({
el: $("#content"),
template: $("#rankings_template").html(),
// Initialiseren
initialize: function(){
self = this;
this.render();
var location_destiny = new google.maps.LatLng(52.476716,4.799623);
var map = new google.maps.Map(document.getElementById('google_maps'), {
center: location_destiny,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: false,
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
overviewMapControl: false
});
if(navigator.geolocation){
navigator.geolocation.watchPosition(update_user_location, error_handler, {
enableHighAccuracy: true,
frequency: 3000
});
} else {
console.error('Geolocation: 0 - Geotracking not available');
}
// Update user location
function update_user_location(position){
location_user = new google.maps.LatLng(52.474716,4.798623);
var marker_user = new google.maps.Marker({
title: 'Gebruiker',
position: location_user,
map: map,
draggable: true,
});
}
// Error handler
function error_handler(error){
console.error('Geolocation: ' + error.code + ' - ' + error.message);
}
var marker_destiny = new google.maps.Marker({
title: 'Bestemming',
position: location_destiny,
map: map,
draggable: true,
});
},
render: function(){
this.$el.html(_.template(this.template));
return this;
}
});
Not sure if I got the question right but for me it helped calling google.maps.event.trigger(map,'resize'); every time after triggering the map route.
PS: a bit late, but maybe it helps someone in the future