How to use fitBounds of GMaps.js - google-maps

I am using GMaps.js and I have several points to show, I need to show all and set the zoom to the point, I was watching the documentation and requests an array of google.maps.LatLng type. I have the following code
for (x in geo){
var item = new google.maps.LatLng(geo[x]["latitud"], geo[x]["longitud"]);
arrayBound.push(item);
}
map = new GMaps({
div: '#divMapa',
lat: latWS,
lng: lngWS,
zoom: 13
});
map.fitBounds(arrayBound);

I didn't find the solution obvious, but, here is an example that works with v0.4.11:
var latlngs = [{lat:"39.158542", lng:"-84.423903"}, {lat:"39.4339357", lng:"-84.9850474"}];
var bounds = [];
for (var i in latlngs) {
var latlng = new google.maps.LatLng(latlngs[i].lat, latlngs[i].lng);
bounds.push(latlng);
map.addMarker({
lat: latlngs[i].lat,
lng: latlngs[i].lng
});
}
map.fitLatLngBounds(bounds);

Rename fitBounds to fitLatLngBounds.

Related

google.maps.LatLng vs google.maps.LatLngLiteral

I am adding google maps to an application I am working on and have successfully gotten myself stuck on a question that may have no impact whatsoever on my application.
Regardless, I am curious why Google Maps allows you to use
new google.maps.LatLng(x, y)
or
{lat: x, lng: y}
I have used both formats and see absolutely no difference but I feel as though I must be missing something... I cannot believe google.map.LatLng exists with no specific purpose.
This:
function initMap() {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom:7,
center: chicago
}
Or this:
function initMap() {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = {lat: 41.850033, lng: -87.6500523);
var mapOptions = {
zoom:7,
center: chicago
}
google.maps.LatLng is the original class (the earliest versions of the API didn't have the google.maps.LatLngLiteral), most but not all, functions that accept a google.maps.LatLng also accept a google.maps.LatLngLiteral ({lat: x, lng: y}).
The advantage of a google.maps.LatLngLiteral is it doesn't require the API to be loaded to use it, it can be used and initialized prior to loading the API.
The advantage of a google.maps.LatLng is that some functions (primarily those in the geometry library) only accept google.maps.LatLng as inputs.

Using freemarker 'list' directive within a google maps function

I have the following list called 'locationList':
[[lat:-6.2986514, lng:53.3324511, car_reg:161-D-XXXXXX], [lat:-7.259881, lng:53.041335, car_reg:151-D-YYYYY], [lat:-7.6273397, lng:53.3052366, car_reg:142-D-ZZZZZ]]
Now, if I just do a simple iteration like this it works. (It outputs my three lines of coordinates.).
<#list locationList as loc>
<p> Output: ${loc.lat} -- ${loc.lng} </p>
</#list>
But when I try to use it within my google maps function, it won't work. This is what I have:
function geocodeLatLng(geocoder, map, infowindow) {
<#list locationList as loc>
var latlng = {lat: ${loc.lat}, lng: ${loc.lng} };
var marker = new google.maps.Marker({
position: latlng,
map: map
});
</#list>
}
It works fine if I just write out manually three times what is contained within the freemarker list tags.
And I have tried everything I can think of. Can anyone help throw light on what is happening here?
EDIT - Whole script included below:
<script>
function initMap() {
<#assign lat='53.328015' lng='-6.3743767' >
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: ${lat}, lng: ${lng} }
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
google.maps.event.addDomListener(window, 'load', function() {
geocodeLatLng(geocoder, map, infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
<#list locationList as loc>
var latlng = {lat: ${loc.lat}, lng: ${loc.lng} };
var marker = new google.maps.Marker({
position: latlng,
map: map
});
</#list>
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=REMOVED&callback=initMap"
async defer></script>
In cases like this, always check what the actual output is (you should be able to do that in the web browser) and how that differs from what you write when you fill it manually. Also, check what JavaScript errors you get.
My blind guess is that the numbers are formatted for human audience, and thus aren't valid JavaScript literals. Use ?c (as in ${loc.lat?c}) to format for computer "audience".
The code was fine. In constructing my list I had got longtitude and latitude the wrong way around. Apologies. I was looking in the entirely wrong place.

How can I move a marker given an array of positions?

I am trying to move a marker to positions stored into an array.
let vehicule_assigne_geo = { lat: 45.495252, lng: -73.605798 };
var image = "img/Sedan-52.png";
let marker = new google.maps.Marker({
position: vehicule_assigne_geo,
map: self.map,
draggable: false,
icon: image,
title: 'Your taxi'
});
//self.tabmarkers is my array of positions
//positions have this format: var LatLng = { lat:steps[c].lat_lngs[i].lat() , lng: steps[c].lat_lngs[i].lng() };
for(var i=0;i<self.tabmarkers.length;i++){
marker.setPosition(self.tabmarkers[i])
}
I can see the marker at the last position of the array.I tried to put o timeout like this
setTimeout(3000)
just after setting the position.But this doesn't change the result.
What am I doing wrong?
Probably you need something like Google Maps' Marker animations with setTimeout() example:
The trick is to multiply the timeout value. Or you may use the setInterval() method.
As you did not gave your entire code, you will need something like this:
for(var i=0; i < self.tabmarkers.length; i++){
moveMarkerWithTimeout(self.tabmarkers[i], i * 1000);
};
function moveMarkerWithTimeout(position, timeout){
window.setTimeout(function() {
marker.setPosition(position);
}, timeout);
}
Haven't tested but it should work.

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