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.
Related
I am trying to create a simple program that takes in specifically two specifically placed destinations and shows the directions in between them. For whatever reason, I just cannot get the directions to show up.
<script>
var directionsService = new google.maps.directionsService();
var directionsDisplay = new google.maps.directionsRenderer();
var new_york = {lat: 40.7128, lng: -74.0060};
var los_angeles = {lat: 34.0522, lng: -118.2437};
function initMap() {
var mapMarkers = [];
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 4, center: {lat: 40, lng: -99}}
);
var marker1 = new google.maps.Marker({
position: new_york,
map: map,
title: 'Home'
});
var marker2 = new google.maps.Marker({
position: los_angeles,
map: map,
title: 'School'
});
}
calculateAndDisplayRoute: function(directionsService, directionsDisplay, new_york, los_angeles) {
directionsService.route({
origin: new_york,
destination: los_angeles,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
alert('Directions request failed due to ' + status);
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDmA98U4We-2IAaHbxa354v_C91IktiSKM3&callback=calculateAndDisplayRoute"></script>
I think there are a few problems with your code, first you need to be aware that the google maps library needs to be loaded before you can create new instances of DirectionsService and DirectionsRenderer, which btw should be in CamelCase:
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
Since you are not loading the maps library asynchronously you can place the script at the top of your page and just drop the callback argument. I've made a few changes to your code, please check it out below (you need to add your api key):
var new_york = {lat: 40.7128, lng: -74.0060};
var los_angeles = {lat: 34.0522, lng: -118.2437};
function initMap() {
var mapMarkers = [];
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 4, center: {lat: 40, lng: -99}}
);
var marker1 = new google.maps.Marker({
position: new_york,
map: map,
title: 'Home'
});
var marker2 = new google.maps.Marker({
position: los_angeles,
map: map,
title: 'School'
});
}
function calculateAndDisplayRoute() {
initMap();
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var route = {
origin: new_york,
destination: los_angeles,
travelMode: 'DRIVING'
};
directionsService.route(route, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
alert('Directions request failed due to ' + status);
}
});
}
calculateAndDisplayRoute();
<script src="https://maps.googleapis.com/maps/api/js?key=???"></script>
<div id="map" style="width: 100%; height: 500px;"></div>
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.
the problem i've got is that I don't know where the problem is :P
From the beginning. I've got 3 files, the json file JS and html. JS should get placeid from json and based on that place a marker on the map. It's all pretty simple but somehow it doesn't work, the map is being created but no markers show up.
Here're the files:
JSON:
[{ "placeid": 'ChIJu6HrLMVWIkcRWHTA90kiueI' , "content": " 1 " } ,
{ "placeid": 'ChIJnXBuJ34zGUcRvt9FTKrPeeM' , "content": " 2 " } ,
{ "placeid": 'ChIJiwUNhqX7PEcRdJjYqzrWYjs' , "content": " 3 " } ]
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
<script src="functions_edit.js"></script>
</head>
<body>
<div id="map-canvas" style="width:500px; height:400px"></div>
</body>
</html>
JS:
var openedInfoWindow = null;
function initialize() {
var latitude = 51.9315631,
longitude = 19.473451,
radius = 8000,
center = new google.maps.LatLng(latitude,longitude),
mapOptions = {
center: center,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
setMarkers(center, radius, map);
}
function setMarkers(center, radius, map) {
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "placeid.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i];
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: data.placeid
}, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
var marker = new google.maps.Marker({
map: map,
place: {
placeId: data.placeid,
location: result.geometry.location
}
//position: result.geometry.location
});
});
infoBox(map, marker, data);
}
}
function infoBox(map, marker, data) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.content);
infoWindow.open(map, marker);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.content);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
With the posted code I get a javascript error: Uncaught ReferenceError: marker is not defined
You are calling the InfoBox function in the wrong place (outside the scope where marker exists).
Once I fix that I get infowindows, but you have an issue that can be solved by function closure (all the infowindows have the content "3", the last marker processed). (For an example of function closure see Google Maps JS API v3 - Simple Multiple Marker Example)
working fiddle
code snippet:
var placeid_json = [{
"placeid": 'ChIJu6HrLMVWIkcRWHTA90kiueI',
"content": " 1 "
}, {
"placeid": 'ChIJnXBuJ34zGUcRvt9FTKrPeeM',
"content": " 2 "
}, {
"placeid": 'ChIJiwUNhqX7PEcRdJjYqzrWYjs',
"content": " 3 "
}];
var openedInfoWindow = null;
function initialize() {
var latitude = 51.9315631,
longitude = 19.473451,
radius = 8000,
center = new google.maps.LatLng(latitude, longitude),
mapOptions = {
center: center,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
setMarkers(center, radius, map);
}
function setMarkers(center, radius, map) {
/* var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "placeid.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})(); */
var json = placeid_json;
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i];
createMarker(data, map);
}
}
function createMarker(data, map) {
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: data.placeid
}, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
var marker = new google.maps.Marker({
map: map,
place: {
placeId: data.placeid,
location: result.geometry.location
}
//position: result.geometry.location
});
infoBox(map, marker, data, result);
});
}
function infoBox(map, marker, data, result) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.content);
infoWindow.open(map, marker);
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.content+"<br>"+result.name);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas" style="width:500px; height:400px"></div>
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);
});
}
}