I want to show Google map in my html . here is my code:
html:
<div class="map-content">
<div map-marker="" ng-model="searchLocation" class="mapmarker"></div>
</div>
js:
app.directive('mapMarker',function(){
return {
restrict: 'EA',
require: '?ngModel',
scope:{
searchLocation: '=ngModel'
},
controller: function ($scope) {
$scope.searchLocation = {
latitude: 48.137273,
longitude: 11.575251
};
},
resolve: {
load: function () {
}
},
link: function(scope , element, attrs , ngModel){
var mapOptions;
var googleMap;
var searchMarker;
var searchLatLng;
ngModel.$render = function(){
searchLatLng = new google.maps.LatLng(scope.searchLocation.latitude, scope.searchLocation.longitude);
mapOptions = {
center: searchLatLng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
googleMap = new google.maps.Map(element[0],mapOptions);
searchMarker = new google.maps.Marker({
position: searchLatLng,
map: googleMap,
draggable: true
});
google.maps.event.addListener(searchMarker, 'dragend', function(){
scope.$apply(function(){
scope.searchLocation.latitude = searchMarker.getPosition().lat();
scope.searchLocation.longitude = searchMarker.getPosition().lng();
});
}.bind(this));
};
scope.$watch('searchMarker', function(value){
var myPosition = new google.maps.LatLng(scope.searchLocation.latitude, scope.searchLocation.longitude);
searchMarker.setPosition(myPosition);
}, true);
}
}
});
Also, I include
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
It knows script file but it can't show map on my html. Any suggestion?
With a little bit of modifications your example works: see my plunkr.
angular
.module('app', [])
.directive('mapMarker',function(){
return {
restrict: 'EA',
scope:{
searchLocation: '=mapMarker'
},
controller: function ($scope) {
$scope.searchLocation = {
latitude: 48.137273,
longitude: 11.575251
};
},
link: function(scope , element, attrs , ngModel){
var mapOptions;
var googleMap;
var searchMarker;
var searchLatLng;
searchLatLng = new google.maps.LatLng(scope.searchLocation.latitude, scope.searchLocation.longitude);
mapOptions = {
center: searchLatLng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
googleMap = new google.maps.Map(element[0], mapOptions);
searchMarker = new google.maps.Marker({
position: searchLatLng,
map: googleMap,
draggable: true
});
google.maps.event.addListener(searchMarker, 'dragend', function(){
scope.$apply(function(){
scope.searchLocation.latitude = searchMarker.getPosition().lat();
scope.searchLocation.longitude = searchMarker.getPosition().lng();
});
});
scope.$watch('searchMarker', function(value){
var myPosition = new google.maps.LatLng(scope.searchLocation.latitude, scope.searchLocation.longitude);
searchMarker.setPosition(myPosition);
}, true);
}
}
});
You don't need ngModel. Especially ngModel.$render. It is needed for inputs, which is not your case.
Container for map has to have initial size: width and height.
Related
I am trying to build a simple Angular 1.5 component containing a Leaflet map.
Here is my component's JS:
// Extend the leaflet js to support the topo module
L.TopoJSON = L.GeoJSON.extend({
addData: function(jsonData) {
if (jsonData.type === "Topology") {
for (var key in jsonData.objects) {
geojson = topojson.feature(jsonData, jsonData.objects[key]);
L.GeoJSON.prototype.addData.call(this, geojson);
}
} else {
L.GeoJSON.prototype.addData.call(this, jsonData);
}
}
});
angular
.module('synthApp')
.component('map', {
templateUrl: 'app/components/map.template.html',
controller: MapController,
bindings: {
name: '#'
}
});
MapController.$inject = [
'$window',
'$rootScope'
];
function MapController(
$window,
$rootScope
) {
var $ctrl = this;
$ctrl.map = null;
$ctrl.markers = [];
// Set layer style
$ctrl.handleLayer = function(layer) {
layer.setStyle({
fillColor: '#eee',
weight: 1,
opacity: 1,
color: '#aaa',
fillOpacity: 1,
clickable: false
});
};
$ctrl.$onInit = function() {
$ctrl.map = $window.L.map($ctrl.name, {
maxZoom: 10,
minZoom: 1,
scrollWheelZoom: false,
attributionControl: false,
tap: false,
touchZoom: true,
zoomControl: true,
crs: $window.L.CRS.EPSG4326
});
var topoLayer = new $window.L.TopoJSON();
var td;
$.getJSON("../map.json", function(json) {
td = json;
console.log(td);
});
topoLayer.addData(td);
topoLayer.addTo($ctrl.map);
topoLayer.eachLayer($ctrl.handleLayer);
$ctrl.map.setView([0,0], 2);
};
}
Here is the content of app/components/map.template.html:
<div id="$ctrl.name" style="background:#c2dfff;height:500px;width:100%">
I am trying to use the component like so:
<map name="rt-world-2"></map>
However, I am seeing an error Error: Map container not found. occurring on the line where I call $ctrl.map = $window.L.map($ctrl.name, {...}) in the map component's init.
Are there some kind of limitations with using Angular in conjunction with Leaflet? Any ideas what the error message means?
In the template:
<div id="$ctrl.name" style="background:#c2dfff;height:500px;width:100%">
replace the binding expression for id attribute with id="{{$ctrl.name}}"
And then wrap the map initialization with $timeout to ensure the template is rendered:
$ctrl.$onInit = function () {
$timeout(function () {
//map initialization goes here..
});
};
Example
angular
.module('synthApp', [])
.component('map', {
//templateUrl: 'map.template.html',
template: '<div id="{{$ctrl.name}}" style="background:#c2dfff;height:500px;width:100%"/>',
controller: MapController,
bindings: {
name: '#'
}
});
MapController.$inject = [
'$window',
'$rootScope',
'$timeout'
];
function MapController(
$window,
$rootScope,
$timeout
) {
var $ctrl = this;
$ctrl.map = null;
$ctrl.markers = [];
$ctrl.$onInit = function () {
$timeout(function () {
$ctrl.map = $window.L.map($ctrl.name, {
maxZoom: 10,
minZoom: 1,
scrollWheelZoom: false,
attributionControl: false,
tap: false,
touchZoom: true,
zoomControl: true,
crs: $window.L.CRS.EPSG4326
});
$ctrl.map.setView([0, 0], 2);
$window.L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{ maxZoom: 18 }).addTo($ctrl.map);
});
};
}
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<script src="//cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<div ng-app="synthApp">
<map name="rt-world-2"></map>
</div>
I am trying to add cluster marker to google maps in angularjs.
I have already included the js file (https://github.com/googlemaps/js-marker-clusterer/blob/gh-pages/src/markerclusterer.js) and the images (https://github.com/googlemaps/js-marker-clusterer/tree/gh-pages/images).
However the cluster still not appears.
This is my code:
html:
<section id="GoogleMaps" ng-controller="MapsController">
<div class="container">
<div>
<div id="map_canvas"></div>
</div>
</div>
</section>
controller:
.controller('MapsController', ['$scope', '$http', function ($scope, $http) {
$scope.loadData = function () {
var url = 'data/LatLng.json';
return $http.get(url).then(function (response) {
return response.data;
});
};
$scope.initMap = function (data) {
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(48.209500, 16.370691),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
data.forEach(function (item) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(item.LAT, item.LON),
animation: google.maps.Animation.Bounce,
map: map
});
var options = {
imagePath: 'images/m'
};
var markerCluster = new MarkerClusterer(map, marker, options);
});
};
$scope.loadData()
.then($scope.initMap);
}])
scripts:
addTag('script', { src: 'http://maps.googleapis.com/maps/api/js' }, sync);
addTag('script', { src: 'assets/js/markerclusterer.js' }, sync);
Any ideas how to add it?
Thank You.
Initialise the MarkerClusterer as following way.
$scope.initMap = function (data) {
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(48.209500, 16.370691),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var markerArray = [];
data.forEach(function (item) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(item.LAT, item.LON),
animation: google.maps.Animation.Bounce,
map: map
});
markerArray.push(marker);
});
var options = {
imagePath: 'images/m'
};
var markerCluster = new MarkerClusterer(map, markerArray, options);
};
When you initialize it in forEach loop, it creates new object of it.
I want to achieve something similar to this http://jsfiddle.net/sya8gn0w/1/.
Now the problem is I have my own custom directive to display map. I want a function in child controller which will achieve above mentioned functionality on some button click.
eg. The place marker functionality triggers only if I click on some button.
Present code -
function ParentCtrl($scope){
var mainCtrl = this;
angular.extend(mainCtrl , {
map: {
center: {
latitude: 18.5,
longitude: 73.85
},
zoom: 13,
markers: [],
events: {
click: function (map, eventName, originalEventArgs) {
var e = originalEventArgs[0];
var lat = e.latLng.lat(), lon = e.latLng.lng();
var marker = {
id: Date.now(),
coords: {
latitude: lat,
longitude: lon
}
};
mainCtrl .map.markers.pop();
mainCtrl .map.markers.push(marker);
console.log(mainCtrl .map.markers);
console.log("latitude : "+lat+" longitude : "+lon);
$scope.$apply();
}
}
}
});
};
I want to move the functionality present in 'click:' part of angular.extend to a function presents in ChildCtrl controller. Is it possible ?
Ortherwise suggest me different approach to achieve this.
I don't know whether my answer going to help you or not.
Recently I worked on GoogleMap, I want to share what I know.
angular.extend(scope, {
map: {
show: true,
control: {},
version: 'uknown',
center: {
latitude: 0,
longitude: 0
},
options: {
streetViewControl: false,
panControl: false,
maxZoom: 10,
minZoom: 1
},
zoom: 2,
dragging: false,
bounds: {},
markers: scope.markers,
doClusterMarkers: true,
currentClusterType: 'standard',
clusterTypes: clusterTypes,
selectedClusterTypes: selectedClusterTypes,
clusterOptions: selectedClusterTypes['standard'],
events: {
tilesloaded: function(map, eventName, originalEventArgs) {},
click: function(mapModel, eventName, originalEventArgs) {},
dragend: function() {}
},
toggleColor: function(color) {
if (color === 'red') {
return '#6060FB';
} else {
return 'red';
}
}
}
Here the statement markers: scope.markers will help to create new markers or to remove old markers.
In "ChildCtrl" you write a function to update scope.markers object of parent controller.
You could declare the function for adding a marker in a separate controller
and then utilize $controller service to inject that controller into another controller:
angular.module('main', ['uiGmapgoogle-maps'])
.controller('MapCtrl', function ($scope,$controller) {
$controller('MarkerCtrl', {$scope: $scope});
angular.extend($scope, {
map: {
center: {
latitude: 42.3349940452867,
longitude:-71.0353168884369
},
zoom: 11,
markers: [],
events: {
click: function (map, eventName, originalEventArgs) {
var e = originalEventArgs[0];
$scope.addMarker(e.latLng);
$scope.$apply();
}
}
}
});
})
.controller('MarkerCtrl', function($scope) {
angular.extend($scope, {
addMarker: function(latLng) {
var marker = {
id: Date.now(),
coords: {
latitude: latLng.lat(),
longitude: latLng.lng()
}
};
$scope.map.markers.push(marker);
}
});
});
Plunker
I used different but better approach to achieve the desired results.
Found this solution on fiddle . Hope this would be helpful for someone else also.
function dragMarkerService(resolveAddressService){
this.placeMarker = function(location, idValue, map){
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(location.latitude, location.longitude),
draggable: true
});
google.maps.event.addListener(myMarker, 'dragend', function (evt) {
location.latitude = evt.latLng.lat();
location.longitude = evt.latLng.lng();
resolveAddressService.resolveAddress(location, idValue)
});
google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
angular.element(idValue).val() = 'Currently dragging marker...';
});
map.setCenter(myMarker.position);
myMarker.setMap(map);
}
};
I'm trying to implement Google maps in Angular / IonicFramework. I'm using a directive, a service, and a controller. I have a map, marker, and geolocation object in $scope. The map object and the marker object in the view updates from the service however the geolocation object doesn't.
The template/view:
<div class="item item-input item-stacked-label item-icon-right">
<div>
Location
<a ng-click="centerOnMe()">
<i class="icon ion-android-locate" style="font-size:24px"></i>
</a>
</div>
<textarea style="margin-top: 0px; margin-bottom: 0px; height: 45px;" placeholder="Location not found." disabled>{{geoloc.addr}}</textarea>
</div>
<div class="item item-input">
<div class="input-label">Map</div>
</div>
<div class="item item-input" style="height:15em;">
<ion-content scroll="false">
<map on-create="mapCreated(map, geoloc, marker)"></map>
</ion-content>
</div>
The map directive:
angular.module('starter.directives', [])
.directive('map', function(MapService) {
return {
restrict: 'E',
scope: {
onCreate: '&'
},
link: function ($scope, $element, $attr) {
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(43.07493, -89.381388),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($element[0], mapOptions);
var geoloc = {
lat: null, lng: null, str: null, brgy: null,
muni: null, reg: null, addr: null
};
var marker = new google.maps.Marker({
map: map
});
$scope.onCreate(
{
map: map, //link map to map in controller
geoloc: geoloc, //link geoloc to geoloc in controller
marker: marker //link marker to marker in controller
});
// Stop the side bar from dragging when mousedown/tapdown on the map
google.maps.event.addDomListener($element[0], 'mousedown', function (e) {
e.preventDefault();
return false;
});
}
if (document.readyState === "complete") {
initialize();
} else {
google.maps.event.addDomListener(window, 'load', initialize);
}
}
}
});
The map controller:
angular.module('starter.controllers', [])
.controller('MapCtrl', function($scope, $ionicLoading, MapService) {
$scope.mapCreated = function(map, geoloc, marker) {
$scope.map = map; //sets the map from the directive to the $scope
$scope.geoloc = geoloc; //sets the geoloc from the directive to the $scope
$scope.marker = marker; //sets the marker from the directive to the $scope
};
$scope.centerOnMe = function () {
console.log('Centering..');
if (!$scope.map && !$scope.marker && !$scope.geoloc) {
return;
}
$scope.loading = $ionicLoading.show({
template: 'Getting current location...',
noBackdrop: true
});
$scope.geoloc = MapService.getCurrentLocation($ionicLoading, $scope.map, $scope.geoloc, $scope.marker);
// ^^^ This doesn't seem to work. $scope.geoloc doesn't get updated immediately, while $scope.map and $scope.marker gets updated immediately. Has to be invoked twice for $scope.geoloc to be updated.
}
});
The map service:
angular.module('starter.services', [])
.factory('MapService', function() {
return {
getCurrentLocation: function($ionicLoading, map, geoloc, marker) {
navigator.geolocation.getCurrentPosition(function (pos) { //callback if get location succeeds
geoloc.lat = pos.coords.latitude;
geoloc.lng = pos.coords.longitude;
var latlngpos = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlngpos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(16);
marker.setOptions({
position: latlngpos,
map: map
});
geoloc.str = results[0].address_components[0].short_name; //type:route
geoloc.brgy = results[0].address_components[1].short_name; //type:neighborhood
geoloc.muni = results[0].address_components[2].short_name; //type:locatlity
geoloc.reg = results[0].address_components[3].short_name; //type:admnistrative_area_level_1
geoloc.addr = results[0].formatted_address;
} else {
console.log('No results found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
map.setCenter(latlngpos);
$ionicLoading.hide();
}, function (error) { //callback if get location fails
alert('Unable to get location: ' + error.message);
});
return geoloc;
}
}
})
;
I based my implementation here:
http://www.jeffvandalsum.com/integrating-google-maps-api-with-angular/
And I already followed the solutions as suggested here, however the $scope.geoloc object still doesn't update:
Angular directive scope between google maps and a controller
Phonegap not firing GoogleMaps v3 domListener function inside Angularjs directive
Try wrapping
$scope.geoloc = MapService.getCurrentLocation($ionicLoading,$scope.map, $scope.geoloc, $scope.marker);
with $timeout
angular.module('starter.controllers', [])
.controller('MapCtrl', function($scope,$timeout, $ionicLoading, MapService) {
$scope.mapCreated = function(map, geoloc, marker) {
$scope.map = map; //sets the map from the directive to the $scope
$scope.geoloc = geoloc; //sets the geoloc from the directive to the $scope
$scope.marker = marker; //sets the marker from the directive to the $scope
};
$scope.centerOnMe = function () {
console.log('Centering..');
if (!$scope.map && !$scope.marker && !$scope.geoloc) {
return;
}
$scope.loading = $ionicLoading.show({
template: 'Getting current location...',
noBackdrop: true
});
$timeout(function(){
$scope.geoloc = MapService.getCurrentLocation($ionicLoading, $scope.map, $scope.geoloc, $scope.marker);
// ^^^ This doesn't seem to work. $scope.geoloc doesn't get updated immediately, while $scope.map and $scope.marker gets updated immediately. Has to be invoked twice for $scope.geoloc to be updated.
});
}
});
Side Note: This isn't necessarily the best way, but it should trigger your $scope.geoloc to to update correctly.
I would also suggest Gajotres's tutorial.
Hope this was helpful!
I just rewrote my directive, service, and controller, and now it's working. the data now is contained in the service. Then I just injected the service to the directive and the controller.
The map service:
.factory('MapService', function() {
var service = {};
service.map = null;
service.marker = null;
service.geoloc = {
lat: 0.0,
lng: 0.0,
str: "",
brgy: "",
muni: "",
reg: "",
addr: ""
};
service.init = function(map, marker) {
this.map = map;
this.marker = marker;
}
service.getCurrLoc = function($ionicLoading) {
navigator.geolocation.getCurrentPosition(function (pos) { //callback if get location succeeds
service.geoloc.lat = pos.coords.latitude;
service.geoloc.lng = pos.coords.longitude;
var latlngpos = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
var geocoder = new google.maps.Geocoder();
service.marker = new google.maps.Marker({
position: latlngpos,
map: service.map
});
//get location
geocoder.geocode({'latLng': latlngpos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
service.map.setZoom(16);
service.marker.setOptions({
position: latlngpos,
map: service.map
});
service.geoloc.str = results[0].address_components[0].short_name; //type:route
service.geoloc.brgy = results[0].address_components[1].short_name; //type:neighborhood
service.geoloc.muni = results[0].address_components[2].short_name; //type:locatlity
service.geoloc.reg = results[0].address_components[3].short_name; //type:admnistrative_area_leveservice
service.geoloc.addr = results[0].formatted_address;
service.map.setCenter(latlngpos);
$ionicLoading.hide(); //hide loading prompt
} else {
console.log('No results found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
},
function (error) { //callback if get location fails
},
{ enableHighAccuracy: true }); //geolocation options
}
return service;
})
The map directive:
.directive('map', ["MapService", function(MapService) {
return {
restrict: 'E',
scope: {
onCreate: '&'
},
link: function ($scope, $element, $attr) {
function initialize() {
var mapOptions = {
//set to Philippines
center: new google.maps.LatLng(14.6839606, 121.0622039),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
MapService.map = new google.maps.Map($element[0], mapOptions);
MapService.marker = new google.maps.Marker({
map: MapService.map
});
$scope.onCreate(
{
map: MapService.map, //link map to map in controller
marker: MapService.marker, //link marker to marker in controller
geoloc: MapService.geoloc //link geoloc to geoloc in controller
}
);
// Stop the side bar from dragging when mousedown/tapdown on the map
google.maps.event.addDomListener($element[0], 'mousedown', function (e) {
e.preventDefault();
return false;
});
}
if (document.readyState === "complete") {
initialize();
} else {
google.maps.event.addDomListener(window, 'load', initialize);
}
}
}
}])
The map controller:
.controller('MapCtrl', ["$scope", "$ionicLoading", "MapService", function($scope, $ionicLoading, MapService) {
$scope.mapCreated = function(map, marker, geoloc) {
$scope.map = map; //sets the map from the directive to the $scope
$scope.marker = marker; //sets the marker from the directive to the $scope
$scope.geoloc = geoloc; //sets the geoloc from the directive to the $scope
console.log('$scope.geoloc in $scope.mapCreated', $scope.geoloc);
$scope.centerOnMe();
};
$scope.centerOnMe = function () {
console.log("Centering");
if (!$scope.geoloc && !$scope.map && !$scope.marker) {
console.log($scope.map);
console.log($scope.marker);
console.log($scope.geoloc);
return;
}
$scope.loading = $ionicLoading.show({
template: 'Getting current location...',
noBackdrop: true
});
MapService.getCurrLoc($ionicLoading);
}
}])
I'm learning backbone and I started to build an application that uses google maps. My problem is that when I try to render google maps in my view nothing happens, only appears the div that contains id="map_canvas" in gray, like this:
and in my console log I have this error Uncaught TypeError: Cannot read property 'setCenter' of undefined
Code of my view:
ev.views.Home = Backbone.View.extend({
map: null,
pos: null,
initialize: function(){
this.template = _.template(ev.templateLoader.get('home'));
this.render();
},
initMap: function(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
//guarda a posicao currente do utilizador
this.pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: this.map,
position: this.pos
});
console.log("a minha posicao eh: " + this.pos);
this.map.setCenter(this.pos);
});
}
var mapOptions = {
zoom: 8,
//center: new google.maps.LatLng(-34.397, 150.644)
};
this.map = new google.maps.Map(this.$el.find('#map_canvas')[0],mapOptions);
},
render: function(){
this.$el.html(this.template());
this.initMap();
return this;
}
});
main.js:
var ev = new Application();
ev.Router = Backbone.Router.extend({
routes: {
"": "home"
},
initialize: function() {
// Caching the Welcome View
this.homeView = new ev.views.Home();
},
home: function () {
$('#home').html(this.homeView.el);
}
});
$(document).on('ready', function() {
// Load HTML templates for the app
ev.templateLoader.load(['shell', 'home'], function () {
ev.shell = new ev.views.Shell({el: "#shell"});
ev.router = new ev.Router();
Backbone.history.start();
});
});
try this I haven't tested:
initMap: function(){
this.map = new google.maps.Map(this.$el.find('#map_canvas')[0],mapOptions);
var that = this;
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
//guarda a posicao currente do utilizador
that.pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: that.map,
position: that.pos
});
console.log("a minha posicao eh: " + this.pos);
this.map.setCenter(this.pos);
});
}
var mapOptions = {
zoom: 8,
//center: new google.maps.LatLng(-34.397, 150.644)
};
},
Try the following code, I hope it will work; I've not tested it.
initMap: function(){
var that= this;
var mapOptions = {
zoom: 8,
//center: new google.maps.LatLng(-34.397, 150.644)
};
this.map = new google.maps.Map(this.$el.find('#map_canvas')[0],mapOptions);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
//NOTE : the scope of 'this' changes to the current function so use the fair copy of it as 'that'
that.pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: that.map,
position: that.pos
});
console.log("a minha posicao eh: " + that.pos);
that.map.setCenter(that.pos);
});
}
}