this.map.getBounds() is undefined - google-maps

I am following the Josh morony's tutorial and
trying to get the bounds information of google map.
But the outcome of getBounds() is "undefined"
How can I get the value of getBounds()?
My developing environment is
"Ionic2 (2.0.0-rc.4) + typescript"
And my code is like below
initMap(): Promise<any> {
this.mapInitialised = true;
return new Promise((resolve) => {
let latLng = new google.maps.LatLng(37.481223, 126.952701);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement, mapOptions);
let bounds = this.map.getBounds();
console.log(bounds); <-- output "undefined"
resolve(true);
});
}
Thanks in advance ! :)

Try this one :)
this.map.getBounds().getSouthWest().lat(),
this.map.getBounds().getNorthEast().lat(),
this.map.getBounds().getSouthWest().lng(),
this.map.getBounds().getNorthEast().lng()

Ensure that your map is initialized and tiles loaded by listening for the tilesloaded event. This code example would output Latitude and Longitude values for and map bounds change such as panning or zooming.
google.maps.event.addListener(this.map, 'tilesloaded', () => {
console.log(this.map.getBounds().getNorthEast().lat());
console.log(this.map.getBounds().getNorthEast().lng());
console.log(this.map.getBounds().getSouthWest().lat());
console.log(this.map.getBounds().getSouthWest().lng());
});

Related

Google maps centered load failure

Well I'm having this problem, load the map once and everything works perfect. The second time or once update the map does not load ok, but not centered load when navigating on you can see the marks that are made but is deformed or simply lost.
I have tried several ways to solve this problem, first and most common I found was to use google.maps.event.trigger(map 'resize') but it did not work then and logic, try that whenever loading map is executed, create a new map, with the same data and focused but neither worked for me. It may be also the way I use the map. I am using the plugin of the camera in my application, the user takes a photo and this should detect where I draw the picture and display the map. Each time the view is opened, the plug of the camera, in the process of taking and show the picture is where I call the appropriate functions to load the map and this has me a bit tricky immediately loaded I have a good time locked in this problem, I found solutions serve me but only for the browser, the device does not work. I am using ionic framework and plugins cordova.
Controller :
.controller("CamaraCtrl", function($scope,$rootScope, Camera,$cordovaGeolocation,$state,$location,$ionicSideMenuDelegate) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var latitud_actual = position.coords.latitude
var longitud_actual = position.coords.longitude
$scope.latitud = latitud_actual;
$scope.longitud = longitud_actual;
//$scope.map = new google.maps.Map(document.getElementById("mapa_ubicacion"), mapOptions);
}, function(err) {
// error
});
function initialize() {
var mapOptions = {
center: new google.maps.LatLng($scope.latitud, $scope.longitud),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
$scope.setMarker(map, new google.maps.LatLng($scope.latitud, $scope.longitud), 'Yo', '');
$scope.map = map;
}
$scope.setMarker = function(map, position, title, content) {
var marker;
var markerOptions = {
position: position,
map: map,
title: title
};
marker = new google.maps.Marker(markerOptions);
google.maps.event.addListener(marker, 'click', function () {
// close window if not undefined
if (infoWindow !== void 0) {
infoWindow.close();
}
// create new window
var infoWindowOptions = {
content: content
};
infoWindow = new google.maps.InfoWindow(infoWindowOptions);
infoWindow.open(map, marker);
});
}
$scope.mostrar_form = false;
$scope.mostrar_boton_view = false;
$scope.getPhoto = function() {
Camera.getPicture().then(function(imageURI) {
console.log(imageURI);
$scope.lastPhoto = imageURI;
$scope.mostrar_form = true;
$scope.mostrar_boton_view = false;
google.maps.event.addDomListener(window, 'load', initialize);
initialize();
}, function() {
$scope.mostrar_boton_view = true;
}, {
quality: 75,
targetWidth: 320,
targetHeight: 320,
saveToPhotoAlbum: false
});
};
$scope.getPhoto();
})
The only solution I found was to create a function that executes the map again. It should not be as optimal but at least it solved my problem.
$scope.centrar = function(){
var mapOptions = {
center: new google.maps.LatLng($scope.latitud, $scope.longitud),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
$scope.setMarker(map, new google.maps.LatLng($scope.latitud, $scope.longitud), 'Yo', '');
$scope.map = map;
}

Remove default markers in google maps

I recently learn t to add custom markers to the Google maps. So i created a route with directions API. After that I added my own markers. Now i am facing a problem where both, the original one and the custom one are showing up. How can i remove the default markers to show my originals one.
Code I wrote to add custom markers
function addmarkers()
{
$.each(order,function(key,value)
{
geocoder.geocode( { 'address': waypts[value]}, function(results)
{
var source = 'images/markers/'+i+'.png';
var latlang = results[0].geometry.location;
var marker = new google.maps.Marker({
position: latlang,
map: map,
icon: source
});
});
});
};
I am calling this function just after the initialize() function
function initialize() // creating maps
{
google.maps.visualRefresh = true;
currentlocation = new google.maps.LatLng(mylat,mylong);
var mapoptions =
{
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: currentlocation
}
map = new google.maps.Map(document.getElementById('map'),mapoptions);
addmarkers();
directionsDisplay.setMap(map);
};
Now you can see in the pic, I am getting both the default as well as the customized markers. Where is this going wrong ?

Google maps and knockoutjs

I am making a single page app where in the second view I need to display the Google map. I am using the Google maps API where the map object is to be created.
var map = new google.maps.Map(mapId, {
zoom: 5,
center: new google.maps.LatLng(55, 11),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
The parameter mapId is giving me a problem. The view contains a div with id say "mapId", but I am not able to get the id and so the map cannot be displayed. I tried HTML binding, attribute binding but it does not work. I am new to knockout. Please suggest some method
You should use a custom binding like so:
ko.bindingHandlers.map = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var mapObj = ko.utils.unwrapObservable(valueAccessor());
var latLng = new google.maps.LatLng(
ko.utils.unwrapObservable(mapObj.lat),
ko.utils.unwrapObservable(mapObj.lng));
var mapOptions = { center: latLng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP};
mapObj.googleMap = new google.maps.Map(element, mapOptions);
}
};
Your HTML would look like this:
<div id="mapDiv" data-bind="style:{width:'300px',height:'300px'},map:myMap"></div>
Finally your view model:
function MyViewModel() {
var self = this;
self.myMap = ko.observable({
lat: ko.observable(55),
lng: ko.observable(11)});
}
Here is a fiddle that does a bit more than what you are asking but should work fine for your case as well.
Here's a good example of using Knockout JS and Google Maps. Hopefully, it will help get you on the right track.
http://www.codeproject.com/Articles/387626/BikeInCity-2-KnockoutJS-JQuery-Google-Maps
I have modified "schmidlop" binding to reset marker on change in inputs (lat long inputs) and marker always in center of map.
Html
<input data-bind="value: mapOne().lat" />
<input data-bind="value: mapOne().lng" />
Binding , Include this in some js file and include it in html.
ko.bindingHandlers.map = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
$("#" + element.getAttribute("id")).data("mapObj","");
mapObj = ko.utils.unwrapObservable(valueAccessor());
var latLng = new google.maps.LatLng(
ko.utils.unwrapObservable(mapObj.lat),
ko.utils.unwrapObservable(mapObj.lng));
var mapOptions = { center: latLng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP};
mapObj.googleMap = new google.maps.Map(element, mapOptions);
mapObj.marker = new google.maps.Marker({
map: mapObj.googleMap,
position: latLng,
draggable: true
});
mapObj.onChangedCoord = function(newValue) {
var latLng = new google.maps.LatLng(
ko.utils.unwrapObservable(mapObj.lat),
ko.utils.unwrapObservable(mapObj.lng));
mapObj.googleMap.setCenter(latLng);
mapObj.marker.setPosition(latLng);
};
mapObj.onMarkerMoved = function(dragEnd) {
var latLng = mapObj.marker.getPosition();
mapObj.lat(latLng.lat());
mapObj.lng(latLng.lng());
};
mapObj.lat.subscribe(mapObj.onChangedCoord);
mapObj.lng.subscribe(mapObj.onChangedCoord);
google.maps.event.addListener(mapObj.marker, 'dragend', mapObj.onMarkerMoved);
$("#" + element.getAttribute("id")).data("mapObj",mapObj);
}
};
View Model
self.mapOne = ko.observable();
self.mapOne({'lat':ko.observable(87.22),'lng':ko.observable(27.22)});
Instead of mapId you'll want to use document.getElementById('map'), where 'map' is the id of the div containing the map (<div id="map"></div>). This jsFiddle should help.

Google Maps HTML5 don't work on my phone (Safari browser)

I'm currently upgrading to the "new" HTML5 version of Google Maps Geolocation API and I have some problems. The function works perfectly on my computer but not on my phone with the Safari browser. The code is as follows:
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var speed = position.coords.altitude;
var coords = new google.maps.LatLng(latitude, longitude);
alert(position.coords.speed);
var mapOptions = {
zoom: 15,
center: coords,
mapTypeControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(
document.getElementById('weather-map'), mapOptions
);
var marker = new google.maps.Marker({
position: coords,
map: map
});
});
} else {
alert('Geolocation API stöds inte i din webbläsare');
}
If I set an alert() right after if(navigator.geolocation) { and update the page on my phone, the alert window will appear but if I move the alert() and set it after navigator.geolocation.getCurrentPosition(... it will not show. I have tested if the browser is capable to this API and it is.
How can I fix this problem?
Thanks in advance.
I got it working! :) I missed some important lines like the functions initialize() and show_position(p) to get the position through Stan Wiechers "geo-location-javascript".

Google Maps Api v3 - set map position in runtime

How can I change position of the map, from where it is pointing now, to ie. 45.00,19.00, but in a runtime, now when map is initialized?
my application have to "jump" from some coordinates to other, so that's why I need this ability.
ok, here it is:
MyMap.map.setCenter(new google.maps.LatLng( 45, 19 ) );
Create that Map object, save it to a variable (i.e. map) and then use map.panTo().
See the reference of Map
you need the extended MVCObject() ....
there you find getPosition() (return: LatLng) and setPosition(latlng:LatLng)
you just need to set this property and map location will change
Define the place where to position
Pass that to map.setCenter()
var map;
function initMap() {
var container = document.getElementById('map');
var options = {
zoom: 18,
gestureHandling: 'cooperative',
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(container, options);
var myPlace = { lat: 23.7266, lng: 90.4216 };
map.setCenter(myPlace);
}