Render google maps with backbonejs - javascript

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);
});
}
}

Related

How can I implement google map in the vue component?

I get reference from here : How to get the formatted address from a dragged marker in Google Version Maps
It using javascript
I want to implement it in the vue component
I try like this :
https://jsfiddle.net/oscar11/1krtvcfj/2/
I don't type code here. Because the code is too much. So you can directly see in jsfiddle
If I click geocode button, there exist error like this :
Uncaught ReferenceError: marker is not defined
How can I solve the error?
new Vue({
el: '#app',
template: `
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" #click="codeAddress()">
</div>
`,
data() {
return {
geocoder: null,
map: null,
marker: null,
infowindow: null
}
},
mounted() {
this.infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
})
google.maps.event.addDomListener(window, "load", this.initialize)
},
methods: {
initialize() {
this.geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(-34.397, 150.644)
let mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions)
google.maps.event.addListener(this.map, 'click', () => {
this.infowindow.close()
});
},
geocodePosition(pos) {
this.geocoder.geocode({
latLng: pos
}, responses => {
if (responses && responses.length > 0) {
this.marker.formatted_address = responses[0].formatted_address
} else {
this.marker.formatted_address = 'Cannot determine address at this location.'
}
this.infowindow.setContent(this.marker.formatted_address + "<br>coordinates: " + this.marker.getPosition().toUrlValue(6))
this.infowindow.open(this.map, this.marker)
});
},
codeAddress() {
let address = document.getElementById('address').value;
this.geocoder.geocode({
'address': address
}, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
this.map.setCenter(results[0].geometry.location);
if (this.marker) {
this.marker.setMap(null);
if (this.infowindow) this.infowindow.close();
}
this.marker = new google.maps.Marker({
map: this.map,
draggable: true,
position: results[0].geometry.location
});
google.maps.event.addListener(this.marker, 'dragend', () => {
this.geocodePosition(this.marker.getPosition());
});
google.maps.event.addListener(this.marker, 'click', () => {
if (this.marker.formatted_address) {
this.infowindow.setContent(this.marker.formatted_address + "<br>coordinates: " + this.marker.getPosition().toUrlValue(6));
} else {
this.infowindow.setContent(address + "<br>coordinates: " + this.marker.getPosition().toUrlValue(6));
}
this.infowindow.open(this.map, this.marker);
});
google.maps.event.trigger(this.marker, 'click');
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
})
You should store globe value in the data of Vue component, and get the value by this.name in you methods.

ionic2- error saving variable to localstorage

I'm using google maps in my ionic2 application which works out correctly. The problem i'm facing now is how to save the formatted address to a the localstorage.
When i reload the page i always get
Uncaught TypeError: Cannot read property 'set' of undefined
Below is my javascript
ionViewDidLoad(){
let loader = this.LoadingController.create({
content: 'Getting your Location'
});
loader.present().then(()=>{
this.geolocation.getCurrentPosition({
enableHighAccuracy:true
}).then((resp) => {
//console.log(resp.coords.latitude)
//console.log(resp.coords.longitude)
this.lng = resp.coords.longitude;
this.lat = resp.coords.latitude;
this.storage.set('user_lng', this.lng);
this.storage.set('user_lat', this.lat);
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(this.lat, this.lng);
geocoder.geocode(
{'latLng': latlng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
this.address= results[0].formatted_address ;
//var value=add.split(",");
console.log("city name is: " + this.address);
this.storage.set('user_location', this.address);
}
else {
alert("address not found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
}
);
let latLng = new google.maps.LatLng(this.lat,this.lng);
let mapOptions = {
center: latLng,
disableDefaultUI: true,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
this.http.get('assets/locations.json').map(res => res.json()).subscribe(data =>{
//console.log(JSON.stringify(data));
this.usermap= data;
let markers= this.usermap;
console.log(JSON.stringify(this.usermap))
//this is to mark user current position on map
//var iconBase = 'assets/';
var mypos_marker = new google.maps.Marker({ position: latLng, map: this.map,title:'My Position',animation: google.maps.Animation.DROP});
mypos_marker.setMap(this.map);
this.myposinfo(mypos_marker);
//this is mark user's routes on map
for(let marker of markers) {
var position = new google.maps.LatLng(marker.latitude, marker.longitude);
var myroutes = new google.maps.Marker({position: position, title: marker.title});
myroutes.setMap(this.map);
this.addInfoWindowToMarker(myroutes);
}
});
})
})
loader.dismiss();
}
addInfoWindowToMarker(marker) {
var infoWindowContent = marker.title;
var infoWindow = new google.maps.InfoWindow({
content: infoWindowContent
});
marker.addListener('click', () => {
infoWindow.open(this.map, marker);
});
}
myposinfo(mypos_marker) {
var infoWindowContent = mypos_marker.title;
var infoWindow = new google.maps.InfoWindow({
content: infoWindowContent
});
mypos_marker.addListener('click', () => {
infoWindow.open(this.map, mypos_marker);
});
}
What i don't understand is the above script this.storage.set('user_lng', this.lng); which saves the user's latitude and longitude to the localstorage work properly
Make sure that you have imported IonicStorageModule inside import section
import { IonicStorageModule } from '#ionic/storage';
#NgModule({
declarations: [
],
imports: [
IonicStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [
],
providers: [
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
this from this.storage where you call it is not the right scope, and it won't contain the property storage. What you want to do is to save the storage in a global variable, before the function call:
import { IonicStorageModule } from '#ionic/storage';
var storage = this.storage;
ionViewDidLoad(){
....
//now replace this.storage with the variable storage
....
}

How to add cluster marker to google maps in angularjs

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.

Multiple markers on google maps using json and placeid

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>

How to add more marker to google map api v3 with dynamic call json

i have an .net mvc 3 website,
in my StoreModel:
public class StoreModels
{
public string StoreName { get; set; }
public decimal LongTit { get; set; }
public decimal LatTit { get; set; }
public int zIndex { get; set; }
}
and in my Home controller
public ActionResult getBeach() {
List<StoreModels> lstStore;
StoreModels strMod = new StoreModels();
lstStore = new List<StoreModels>() {
new StoreModels(){ StoreName = "cua hang 1",
LatTit=20.998324m,
LongTit=105.813708m,
zIndex=1
},
new StoreModels(){ StoreName = "cua hang 2",
LatTit=220.998485m,
LongTit=105.812903m,
zIndex=2
},
new StoreModels(){ StoreName = "cua hang 3",
LatTit=20.982342m,
LongTit=107.887392m,
zIndex=3
}
};
return Json(lstStore, JsonRequestBehavior.AllowGet);
}
and in my index:
<script type="text/javascript">
$(document).ready(function () {
// execute
(function () {
// map options
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(20.998825, 105.81473),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var image = {
url: 'img/here.png',
size: new google.maps.Size(50, 50),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 32)
};
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
var infowindow;
$.getJSON('Home/getBeach', null, function (model) {
for (var i = 0; i < model.length; i++) {
var myLatLng = new google.maps.LatLng(model[i].LatTit,model[i].LongTit);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: model[i].StoreName,
zIndex: i + 1,
});
google.map.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.open(map, marker);
}
})(marker, i));
}
});
})();
});
i saw some example for process that in here and here but in my website, only one marker show on the maps.
Any help is greatly appreciated!
Looks like you problem might be with the longitude/latitude data. Trying passing them in without the m at the end.
new StoreModels(){ StoreName = "cua hang 2",
LatTit=220.998485,
LongTit=105.812903,
zIndex=2
}
or change this line of Javascript by adding in parseFloat() to do the same thing:
var myLatLng = new google.maps.LatLng(parseFloat(model[i].LatTit),parseFloat(model[i].LongTit));

Categories