fitBounds does not center correctly - javascript

When I initialize the map I add 1 marker to the map. When I zoom the map out I can see the added marker multiple times on the map 'copies'.
When I then search for a location the map it adds a new marker.
After that I use fitBounds to fit the two markers on the map.
Normally this would result in the following:
But sometimes it does this:
I have the feeling the fitBounds method sometimes uses the marker on 'the other world'.
The latitude and longitude for both markers are correct and as you can see there are now 2 markers on the left.
Can someone please explain to me why this happens and how I can avoid/fix it?
Here is a part of the search submit function where I calculate the bounds:
var searchResultLocation = mapSearchPlaces[0].geometry.location;
//Create search marker
marker = new google.maps.Marker({
position: searchResultLocation,
animation: google.maps.Animation.BOUNCE,
map: map
});
searchMarkers.push(marker);
//Find map bounds
var closestMarker = null;
var closest = Number.MAX_VALUE;
for (var i=0; i < markerLocations.length; i++) {
var distance = google.maps.geometry.spherical.computeDistanceBetween(searchResultLocation, markerLocations[i]);
if (distance < closest) {
closest = distance;
closestMarker = markerLocations[i];
}
}
var bounds = new google.maps.LatLngBounds(searchResultLocation, closestMarker);
map.fitBounds(bounds);

The google.maps.LatLngBounds constructor take two very specific arguments, in a specific order:
LatLngBounds(sw?:LatLng, ne?:LatLng) | Constructs a rectangle from the points at its south-west and north-east corners.
You should create an empty LatLngBounds object and extend it with the two points:
var bounds = new google.maps.LatLngBounds();
bounds.extend(searchResultLocation);
bounds.extend(closestMarker);
map.fitBounds(bounds);

Related

Add multiple parentLines to a leaflet marker

I'm trying to create a straight line network in Leaflet, which at each junction has a marker, and on drag of each marker, update the position of the corresponding polyline which connects to it.
I've done some research (mostly this question) & reworked a fiddle to strip it down a bit to try & get it to do what I want. I am able to draw the network with individual polylines, however, I need to add multiple parentLines to the marker which is connected to two polylines. I can't find it in the Leaflet documentation, but punted with this:
marker_arr[1].parentLine = [polyline_a,polyline_b];
My issue is when I call the dragstart/drag/dragend handlers, it doesn't work with multiple polylines. (Edit) I have made some headway in capturing the parentLines as an array, but can only make it work for the first parentLine
function dragHandler(e) {
var polyline=[]
console.log("drag")
if(e.target.parentLine.length){
polyline.push(e.target.parentLine[0]);
} else {
polyline.push(e.target.parentLine);
}
if(polyline){
var latlngPoly = polyline[0].getLatLngs(), // Get the polyline's latlngs
latlngMarker = this.getLatLng(); // Get the marker's current latlng
latlngPoly.splice(this.polylineLatlng, 1, latlngMarker); // Replace the old latlng with the new
polyline[0].setLatLngs(latlngPoly); // Update the polyline with the new latlngs
}
}
Can anyone point me to either the documentation about parentLine, or how I might make this work? Using Leaflet v1.6.0 and cannot use more recent versions as this is to extend an already existing implementation of Leaflet based on 1.6.
Fiddle here
Here is a sample.
Add to the marker the parentLines always as array:
marker_arr[0].parentLine = [polyline_a];
marker_arr[1].parentLine = [polyline_a,polyline_b];
marker_arr[2].parentLine = [polyline_b];
and then loop through all parentLines in the dragstart handler:
// Now on dragstart you'll need to find the latlng from the polyline which corresponds
// with your marker's latlng and store it's key in your marker instance so you can use it later on:
function dragStartHandler(e) {
var marker = e.target;
marker.polylineLatlng = {};
e.target.parentLine.forEach((line)=>{
var latlngPoly = line.getLatLngs(), // Get the polyline's latlngs
latlngMarker = marker.getLatLng(); // Get the marker's current latlng
for (var i = 0; i < latlngPoly.length; i++) { // Iterate the polyline's latlngs
if (latlngMarker.equals(latlngPoly[i])) { // Compare marker's latlng ot the each polylines
marker.polylineLatlng[L.stamp(line)] = i; // If equals store key in marker instance
}
}
})
}
And in the drag handler:
// Now you know the key of the polyline's latlng you can change it
// when dragging the marker on the dragevent:
function dragHandler(e) {
var marker = e.target;
e.target.parentLine.forEach((line)=>{
var latlngPoly = line.getLatLngs(), // Get the polyline's latlngs
latlngMarker = marker.getLatLng(); // Get the marker's current latlng
latlngPoly.splice(marker.polylineLatlng[L.stamp(line)], 1, latlngMarker); // Replace the old latlng with the new
line.setLatLngs(latlngPoly); // Update the polyline with the new latlngs
})
}
And clean it in the dragend handler:
// Just to be clean and tidy remove the stored key on dragend:
function dragEndHandler(e) {
var marker = e.target;
delete marker.polylineLatlng;
console.log("end");
}

Remove marker from Gmap

I'm trying to integrate Gmaps in my application, drawing front-end using ExtJs 6.0, and I want to show and hide some user position inside the map.
Adding a marker with user position is quite easy (though I get some strange Cannot read property 'getBounds' of undefined, but I think that's not a big deal).
On the other side, removing a marker it's revealing a little bit more complicated than I thought.
I've read some questions on Stack and Google's Documentation on add/remove markers, and I understand that the "right" way to do it is calling
marker.setMap(null);
But I got a strange behaviour: the marker won't disappear and remains on the map.
This is how I add the marker on the map:
addMarker : function(record) {
var me = this;
var map = me.lookupController().lookupReference('map');
var latitude = record.get('latitude');
var longitude = record.get('longitude');
var description = record.get('fullName');
var marker = new google.maps.Marker({
lat: latitude,
lng: longitude,
title : description
});
me.lookupViewModel().get('techniciansMaker').push(marker);
map.addMarker(marker);
}
And this is how I try to remove marker from the map:
removeMarker : function(record){
var me = this;
var markers = me.lookupViewModel().get('techniciansMaker');
for(var i = 0; i < markers.length; i++){
var m = markers[i];
if (markers[i].getTitle() == record.get('fullName')){
markers[i].setMap(null);
Ext.Array.remove(markers, markers[i]);
}
}
}
Also I'm keeping markers in a list to recognize which one I have to delete.
I can't figure out what I'm doing wrong....
EDIT - SOLVED
I figured out by myself that I was pointing to map container and not the map itself.
Calling map.gmap did the trick.
When using Ext.ux.GMapPanel you should not create the marker yourself with new google.maps.Marker(). Instead addMarker will do this and make listeners:{click:...} work on the marker. You pass the config to addMarker which returns a marker object:
markerConfig = {
lat: latitude,
lng: longitude,
title : description
}
marker = mapPanel.addMarker(markerConfig)
// hide the marker
marker.setMap(null)
// show it again
marker.setMap(mapPanel.gmap)
This allows you to remove the marker and gets rid of that TypeError: Cannot read property 'getBounds' of undefined.

Google Maps v3 - Setting bounds to center of markers

Despite spending all day searching and trying numerous code methods I am still having problems with trying to center and zoom a google map correctly.
I wonder if someone would be so kind as to point out the obvious as to what Im doing wrong in my code. Everything worked fine in v2 but Im having difficulty updating to v3.
For information
The map is a small part of a much larger php application, and the needed lat & long map parameters have already been obtained by other methods which are used in the main prog and declared as follows:-
var myDestination=new google.maps.LatLng(e_lat,e_long);
var myHome=new google.maps.LatLng(h_lat,h_long);
Everything seems to be working ok aside from the zoom and center.
Problematic Code is as follows:-
function initialize()
{
// set the map properties
var mapProp = {
center:myHome,
zoom:12,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
// set the home marker
var marker_home=new google.maps.Marker({
position:myHome,
icon:'house.png'
});
marker_home.setMap(map);
//set the destination marker
var marker_destination=new google.maps.Marker({
position:myDestination,
icon:'flag_red.png'
});
marker_destination.setMap(map);
//google polyline between the 2 points
var myPolyline = [myDestination,myHome];
var directPath = new google.maps.Polyline({
path:myPolyline,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2
});
directPath.setMap(map);
// Make an array of the LatLng's of the markers you want to show
var LatLngList = array (new google.maps.LatLng (e_lat,e_long), new google.maps.LatLng (h_lat,h_long));
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds ();
// Go through each...
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend (LatLngList[i]);
}
// Fit these bounds to the map
map.fitBounds (bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
TIA for any help :)
In your code "array" is not defined. See jsFiddle.
var LatLngList = array (new google.maps.LatLng (e_lat,e_long), new google.maps.LatLng (h_lat,h_long));
You should use
var LatLngList = new Array(new google.maps.LatLng...)
or
var LatLngList = [new google.maps.LatLng...]

google maps javascript api v3 places library doesn't return any results for the bounds

I am trying to use the places library to display markers between two coordinates using the LatLngBounds class. I am able to see a few markers if I comment out the name attribute which is starbucks in the places search request.Can someone please guide me with the following:
1) Currently the markers I see are in the middle of the two coordinates and not evenly distributed along the bounds which I assume creates a rectangle in which you must see them. I think the markers are just being calculated for the the center.
2) When I provide the attribute 'name' and the value "starbucks" I do not see any markers on the map.
I think my bounds object is fine because when I debug I am able to see the northwest and southwest coordinates inside. The coordinates are
34.0522342,-118.2436849 -Los Angeles,CA
33.7489954,-84.3879824 -Atlanta, GA
Can someone guide me where I am going wrong.
function useCordinates(){
...
var defaultBounds = new google.maps.LatLngBounds();
var places = [];
places.push(new google.maps.LatLng(latLongSrc[0],latLongSrc[1]));
places.push(new google.maps.LatLng(latLongDest[0],latLongDest[1]));
defaultBounds.extend(places[0]);
defaultBounds.extend(places[1]);
//var center = defaultBounds.getCenter();
//defaultBounds.contains(center);
var request = {
//attribute to be commented
name:"starbucks",
bounds: defaultBounds,
types:['establishment']
};
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
}
Your bounds is a very narrow rectangle that stretches between Los Angeles and Atlanta (not I think what you want):
http://www.geocodezip.com/v3_GoogleEx_place-search_starbucks.html
Places requests which target the whole country are problematic, you only get 20 results, looks like you might be correct that they are centered on the bounds, and there don't seem to be any "real" starbucks close enough to there to be found:
http://www.geocodezip.com/v3_GoogleEx_place-search_starbucks2.html
If you search in Seattle, WA however, you get some:
http://www.geocodezip.com/v3_GoogleEx_place-search_starbucks3.html

Google Maps: How to zoom out to all locations on map

I am developing am app that shows a list of different places using google maps, i have everything working fine and working with currentLocation and the closestsLocation and it zooms to show this, but I have tried to change this to set it so that it zooms out to show all the buildings and not just the closest one
EDIT: this is the working code
// Sets the bounds of the map to include at lease one visable marker
function setBounds(){
if ( markerCluster.getMarkers().length > 0 && homeMarker != null){
map.setZoom(17);
var visableMarkers = markerCluster.getMarkers();
// want to set the starting position at the homeMarker
//Make an array of the LatLng's of the markers you want to show
var LatLngList = new Array ();
LatLngList.push(homeMarker.position);
$.each(visableMarkers, function() {
LatLngList.push(this.position);
});
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds ();
// Go through each...
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend (LatLngList[i]);
}
// Fit these bounds to the map
map.fitBounds (bounds);
}
}
The code for your array LatLngList is incorrect, I think it should say
var LatLngList = new Array (new google.maps.LatLng (52.537,-2.061), new google.maps.LatLng (52.564,-2.017));

Categories