Leaflet map won't fit bounds - javascript

I'm trying to fit a map to bounds defined by a 2D array. I keep getting the error Error: Bounds are not valid. leaflet.js:5:21909 even though the markers are added to the map and are valid coords.
var map = L.map('map', { zoomControl:false });
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
map.setView([0, 0], 2);
var markers = new L.FeatureGroup();
map.addLayer(markers);
function drawResults(){
// get offer keys
var offers = new Array();
var articles = [];
offersRef.once("value", function(snapshot) {
var offerKeys = Object.keys(snapshot.val());
for (var i=0; i<offerKeys.length; i++){
var offer = snapshot.val()[offerKeys[i]];
var lat = offer.lat;
var lng = offer.lng;
console.log(lat);// outputs 33.2321
console.log(lng);// outputs 101.1234
offers.push([lat, lng]);
var marker = L.marker([lat, lng]).addTo(markers);
}
});
map.fitBounds(markers.getBounds());
}
console.log(offers);
}
drawResults();
Can anyone see what I'm doing wrong?
Edit:
Console logs
35.0721909 app.js:350:13
-106.48798399999998 app.js:351:13
35.0526641 app.js:350:13
-78.87835849999999 app.js:351:13

You will need to move the call to map.fitBounds into the callback, as the once method (which looks like a Firebase API call) is likely asynchronous:
offersRef.once("value", function(snapshot) {
var offerKeys = Object.keys(snapshot.val());
for (var i = 0; i < offerKeys.length; i++) {
var offer = snapshot.val()[offerKeys[i]];
var lat = offer.lat;
var lng = offer.lng;
offers.push([lat, lng]);
var marker = L.marker([lat, lng]).addTo(markers);
}
map.fitBounds(markers.getBounds());
});
If it's called outside the callback, there won't be any markers in the feature group and the group's bounds won't be valid.

Related

get NE and SW corners of a set of markers on a google map

I want to get NE and SW corners of a set of markers on a google map. Here I iterate over each marker. Does google or javascript provide a function that gets this with less iteration?
function fnSetBounds(){
var lowLat = 90;
var highLat = -90;
var lowLng = 180;
var highLng = -180;
for (var i = 0; i < myMarkers.length; i++) {
var myLat = myMarkers[i].position['k'];
var myLng = myMarkers[i].position['B'];
// catch low LAT
if (lowLat > myLat){
lowLat = myLat;
}
// catch high LAT
if (highLat < myLat) {
highLat = myLat;
}
// catch low LNG
if (lowLng > myLng){
lowLng = myLng;
}
// catch high lng
if (highLng < myLng) {
highLng = myLng;
}
}
var southWestCorner = new google.maps.LatLng(highLat, lowLng);
var northEastCorner = new google.maps.LatLng(lowLat, highLng);
var bounds = new google.maps.LatLngBounds();
bounds.extend(southWestCorner);
map.fitBounds(bounds);
bounds.extend(northEastCorner);
map.fitBounds(bounds);
}
I would do it this way, add all the positions to an empty bounds:
function fnSetBounds(){
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < myMarkers.length; i++) {
bounds.extend(myMarkers[i].getPosition());
}
map.fitBounds(bounds);
}

How to delete a direction markers in google map API

I want to delete a google map direction markers after a search without reloading the page. I've made an example but its not working :
//First of all testing if there is already a direction on the map
if(directionsService != null)
{
directionsService.setMap(null);
directionsService = null;
}
//Then display the new one
var origin = $('#de').val();
var destination = $('#en').val();
var request = {
origin : origin,
destination : destination,
travelMode : google.maps.DirectionsTravelMode.DRIVING
}
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status){
if(status == google.maps.DirectionsStatus.OK){
direction.setDirections(response);
showSteps(response);
}
});
all this code is on a function called by a click event
<button id="envoyer" id=="env" onclick="javascript:c()">Send</button>
so any one have an idea thanks !
Update
function showSteps(directionResult) {
var markerArray = [];
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_location,
map: map
});
attachInstructionText(marker, myRoute.steps[i].instructions);
markerArray[i] = marker;
}
}
When clearing the itinerary, using directionsService.setMap(null); you will have to remove the MapMarkers, which aren't directly connected to the Direction - Service, seperately too.
You have already stored them in markerArray inside of your showSteps - function, so you would need to move this variable out of the function into an outer scope or let the function return it to be able to access it.
By doing this, you can simply loop over the markerArray and call .setMap(null) on each stored Marker, thus removing them from the map.
var markerArray = [];
function showSteps(directionResult){
// your code
}
//function to remove MapMarkers
function removeMapMarkers(){
for(var i=0; i<markerArray.length; i+=1){
markerArray[i].setMap(null)
}
markerArray = [];
}

Google map not getting centered

The google map i am using does not get centered about the mean point i have calculated.
The code for the initialization is given. The map appears to be zoomed out a lot and its center far off from the center i have calculated. The mean appears in the extreme top left of the map. What is the problem here?
I am displaying the map in Bootstrap modal.
function initializeMap()
{
var xMean = 0.0;
var yMean = 0.0;
for(var i=0;i<points.length;i++)
{
xMean += parseFloat(points[i][0]);
yMean += parseFloat(points[i][1]);
}
xMean /= parseFloat(points.length);
yMean /= parseFloat(points.length);
var myMean = new google.maps.LatLng(xMean, yMean);
var mapOptions = {
zoom:17,
center:myMean
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i<points.length;i++) {
path.push(new google.maps.LatLng(points[i][0],points[i][1]));
bounds.extend(path[i]);
};
map.fitBounds(bounds);
//Displaying the markers
var marker;
for (var i = 0; i < path.length; i++) {
marker = new google.maps.Marker({
position: path[i],
map: map
});
}
//Displaying the path
for (var i = 0; i<path.length-1; i++) {
var start = path[i];
var end = path[i+1];
requestDirections(start,end);
}
}
by using:
map.fitBounds(bounds);
map.setCenter(bounds.getCenter());
you seem to overwrite myMean coordinates

How do i get back (display) the elevation points on the alert pop up.

I want to get back the elevation values from the code on the alert pop up like i am able to get the values of lat and lng. i am trying to get the three values (lat, lng and elevation heights) in an array so that i can later display the values using OpenGL but i am stuck on this part only as everything is working fine. This is the code i am using. thanks
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var nw = new google.maps.LatLng (ne.lat(), sw.lng());
var se = new google.maps.LatLng(sw.lat(), ne.lng());
for(var i = 0 ; i<= (ne.lat() - sw.lat()); i+=0.01)
{ for(var j =0 ; j<=(ne.lng() - sw.lng());j+=0.01)
{
var tmpele; //temp variable for elevation<br/>
lt.push(sw.lat()+i);<br/>
ln.push(sw.lng()+ j);<br/>
var d = new google.maps.LatLng((sw.lat()+i),(sw.lng()+ j));
loca.push(d);
el.push(pospoint(loca));
} }
alert(lt);
alert(ln);
alert(el);
}
function disp()
{
alert(el);
}
function pospoint(loca)
{
var tmp;
var positionalRequest = {
'locations': loca
}
elevationService.getElevationForLocations(positionalRequest, function(results, status) {
if (status == google.maps.ElevationStatus.OK) {
tmp=results;
// alert('got:'+tmp);
// return tmp;
}
});
return tmp;
}
The elevation service is asynchronous. You can't return anything from it, you can only use the data (when it is available) in the callback function.

IE throws errors parsing data for GoogleMap

I have added map displaying some elements with specific geo position using Google.API. In modern browsers everything works fine, but IE7/8 as always has some problems. When trying to center map using lat/long parameters of each element I'm getting error stating , that 'lat' is "empty or not an object" in line var pos_lat = parseFloat(data_map[i]['lat']);. Still marker is added in the proper place using the same data. Anyone had this kind of problem ?
<script type='text/javascript'>
var map;
var mapStart = function(){
if(GBrowserIsCompatible()){
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(51.961869,19.134521),6);
map.addControl(new GLargeMapControl());
var icon1 = new GIcon();
icon1.image = "/static/images/map_icon_1.png";
icon1.iconSize = new GSize(36, 30);
icon1.infoWindowAnchor = new GPoint(16,16);
icon1.iconAnchor = new GPoint(16,16);
var data_map = [{'url': '/bo/properties/property/7/', 'lat': '52.1898985', 'long': '20.8461914', 'name': 'asdfgh'},]
mapa.enableDoubleClickZoom();
mapa.enableContinuousZoom();
var bounds = new GLatLngBounds();
var maxlng =0;
var maxlat=0;
var minlng=0;
var minlat=0;
var positions=0;
var zoom = 0;
for (var i=0; i < data_map.length; i++){
var pos_lat = parseFloat(data_map[i]['lat']);
var pos_lon = parseFloat(data_map[i]['long']);
if(!isNaN(pos_lat) && !isNaN(pos_lon)){
positions = 1;
zoom++;
addMarker(pos_lat, pos_lon,{icon:icon1});
if (pos_lat < minlat || minlat==0){ minlat = pos_lat}
if (pos_lat > maxlat || maxlat==0){ maxlat = pos_lat}
if (pos_lon < minlng || minlng==0){minlng = pos_lon}
if (pos_lon > maxlng || maxlng==0){maxlng = pos_lon}
lat = minlat + (( maxlat - minlat)/2);
lng = minlng + (( maxlng - minlng)/2);
var allpoints = new GLatLng(lat,lng);
bounds.extend(allpoints);
}
}
if(positions){
if(zoom > 2){
mapa.setZoom(map.getBoundsZoomLevel(bounds)-2);
}
else{
map.setZoom(10);
}
map.setCenter(bounds.getCenter());
}
}
}
var addMarker = function(lat, lon, options){
point = new GLatLng(lat,lon);
var marker = new GMarker(point, options);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(info_box_html);
});
map.addOverlay(marker);
}
$(document).ready(function(){
mapStart();
});
window.onunload = function (){ GUnload()};
</script>
var data_map = [{'url': '/bo/properties/property/7/', 'lat': '52.1898985', 'long': '20.8461914', 'name': 'asdfgh'},]
There is an extra comma at the end of array.
Also try to use data_map[i].lat instead of data_map[i]['lat']

Categories

Resources