Google maps Polyline latitude 0, longitude 0 issue - google-maps

I'm trying to display a tractor's route in google maps and having the following problem (I like to call it "The Guinea Problem":
http://i901.photobucket.com/albums/ac215/MigerusanTTE/coordserrorfinal.jpg
In the pic you can see that the starting point of my polyline starts from lat 0, long 0. I dont know why this is happening because on my while loop I put an alert when it starts and the latlng values are correct when it begins...
Here you have a portion of the code for markers and polylines:
//If i==0 (my FOR variable for looping), coords_prev=coords.
//alert(coords); //alert I put to see what was happening D:
var marker = new google.maps.Marker(
{
position: coords,
map: map,
icon:direccion_ico
});
}
//contructing the line
var line = [coords_prev, coords];
var polyline = new google.maps.Polyline({
path: line,
strokeColor: color,
strokeOpacity: 0.6,
strokeWeight: 3
});
linesArray.push(polyline);
polyline.setMap(map);
coords_prev = coords; //I equal these for the next loop
Tell me what you think...and If I forgot to mention something important too.

On the line
var line = [coords_prev, coords];
This is fine for the second point, but for the very first point, you won't have anything in coords_prev. Thus, for the very first segment, it will start at 0,0 and go to coords.

Related

Make polyline to show on google map horizontally and zoom it to center coordinate

I am using Google Maps API JavaScript. My use case is I need to plot coordinates (lat, lng) on maps (create markers) and join them through polyline. The co-ordinates will be very close to each other so when I try to plot them, they get hidden behind the first marker. So I find out the center and try to zoom so that all markers will be visible on the map.
I used bounds to find the center but I am not able to zoom it to center co-ordinate. I used map.fitBounds(latlng); It fits the coordinate on the screen.
But what I want to achieve is to make polyline (connecting all co-ordinate) always horizontal and zoom it to center co-ordinate.
enter code herevar bounds = new google.maps.LatLngBounds();
for (i = 0; i < temp.length; i++) {
bounds.extend(temp[i]);
}
var latlng = bounds.getCenter();
map.setCenter(latlng);
As the coordinate will always be different, The polyline will be in any direction, but I always want to show it horizontally on the map.
what I get :
enter image description here
what i want to acheive:
enter image description here
Any suggestion will be appreciated.
Thanks in Advance.
I achieve something like this by using the following:
Use computeHeading() function of Geometry library to get the angle from your first to your last coordinate on the line. Make sure to add &libraries=geometry to your Maps JS script tag.
Once you get the heading, you can use the map.setHeading() function to change the angle of your view and after some testings,I can see that you can achieve the horizontal view by subtracting it to 90 degrees.
Here's the sample code and code snippet below:
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: 40.756795,
lng: -73.954298
},
zoom: 16,
tilt: 47.5,
mapId: "90f87356969d889c",
});
//array of your points
const markerCoordinates = [
{ lat: 40.758481, lng: -73.958269 },
{ lat:40.754649, lng: -73.949563 },
];
//creating marker from your points
for (let i = 0; i < markerCoordinates.length; i++) {
const marker = markerCoordinates[i];
new google.maps.Marker({
position:marker,
map,
});
}
//creating polyline from your points
const createdPolyline = new google.maps.Polyline({
path: markerCoordinates,
geodesic: true,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
});
createdPolyline.setMap(map);
//get the heading(angle) of the first coordinate from the last coordinate
const heading = google.maps.geometry.spherical.computeHeading(
markerCoordinates[0],
markerCoordinates[1]
)
//once you get the heading subtract it by 90 to get a horizontal view
map.setHeading(heading-90)
}

How to get the nearest marker on the polyline?

I need to get the nearest marker when I move the mouse over the polyline.
The markers are on the same polyline.
The markers are hidden, and I want to display the nearest to the mouse one, then the next one and to hide the prev one.
Thanks
// SET PATH
var Path = new google.maps.Polyline({
geodesic: true,
strokeColor: '#993300',
strokeOpacity: 1.0,
strokeWeight: 4 ,
id: 123
});
Path.setMap(map);
var path = Path.getPath();
data.map(function(val){
path.push(new google.maps.LatLng(+val.lat, +val.lon));
Path.setPath(path);
})
google.maps.event.addListener(Path, 'mousemove',function(e){
console.log(e.latLng)
})
Firstly you need to make sure you need to load the geometry library when you load your google maps JavaScript API.
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">
</script>
Then, when you mouse over your polyline, loop over your markers and get the distance to all of them from the mouseover point (because you don't know which one is the closest until you check them all).
Here's one way to do it:
//your markers in an array
var markers = [];
google.maps.event.addListener(polyline,'mouseover',function(e) {
var closestMarker;
markers.reduce(function(carry,marker) {
var d = google.maps.geometry.spherical.computeDistanceBetween(marker.getPosition(),e.latLng);
if(d < carry || carry == -1) {
closestMarker = marker;
return d;
}
return carry;
},-1);
//your marker is now in the variable closestMarker
});
You can figure out how to hide and display markers very easily using the Google Maps JavaScript API marker methods

How to get an array of points that would build a Polygon google map

I want to build a polygon area as pictures using google MAP, you can know how to get the array of coordinates for the area?
picture of desired polygon
You can build a Polygon using an array of lat, lng couples of at least 3 elements.
If the array isn't close, Google Maps will close it by default.
While for the most of DBMS, you must save an array of coordinates that is closed. What does close mean? Essentially, the first and the last points of the array are equal. DBMS like MongoDB will throw an error for bad formatted geospatial data. MongoDB Documentation on $polygon.Another thing to mention is that, MongoDB accepts ONLY lng, lat formatted coordinates.
As you can see from Official Google Maps Documentation on Polygons you can draw a Polygon starting from an array of coordinates:
// Define the LatLng coordinates for the polygon.
var triangleCoords = [
{lat: 25.774, lng: -80.190},
{lat: 18.466, lng: -66.118},
{lat: 32.321, lng: -64.757}
];
Then you can construct it and set it on the map:
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords, //Array of Coordinates
strokeColor: '#FF0000', //Color of the line
strokeOpacity: 0.8, //Color opacity
strokeWeight: 3, //Line weight
fillColor: '#FF0000', //Inner Color
fillOpacity: 0.35 //Inner color opacity
});
//Set it on the map
bermudaTriangle.setMap(map);
Then, you can add information to your polygon using clickListener and infoWindows
// Add a listener for the click event and opens infoWindow
bermudaTriangle.addListener('click', showArrays);
infoWindow = new google.maps.InfoWindow;
You can read more about infoWindows here.
Finally, here you can find a Plunker I made up using Google Maps Docs and AngularJS. Of course you can do it with pure Javascript.
Last but not least, make sure of having points on the boundaries and with reasonable lat, lng coordinates.
I hope I've been helpful.

how to draw draggable direction using encoded overview polylines

I want to draw drag gable route on Google map using encoded poly line string.So that i can drag route , make changes in it and save in database. can anyone have idea regarding this?????
ex: I have following encoded polyline
var encodedPath='iqgnAa|lxMDq##]j#CrIKhBClEIrFMe#oCCKBa#VqAbAqCEWIi#MSg#[oAu#kAu#aAe#{#WcAScA]g#Mm#EaAV_ECKxBl#BL#FDKpB';
var path = google.maps.geometry.encoding.decodePath( encodedPath );
var polyline = new google.maps.Polyline({
path: path,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 2.0,
strokeWeight: 8
});
polyline.setMap( map );
I want to draw drag gable path on Google map using this encoded poly line path.
Currently i am able to draw poly line on Google map using following code but its is not drag gable
Any suggestions????
also i want draggable behavior like Google map direction service so that i can deviate the existing path and save for future use
You can make it draggable in the constructor
var polyline = new google.maps.Polyline({
path: path,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 2.0,
strokeWeight: 8,
draggable: true
});
or later as
polyline.setDraggable(true);
or
polyline.set('draggable',true);
If you use the polyline to render Google's direction services, the paths will be updated along with the polyline when you drag it. Keep in mind that after doing this you will need to persist the new polyline path to the database. This is done by adding listeners to the polyline path
google.maps.event.addListener(polyline.getPath(), 'set_at', function () {
var encodedpath=google.maps.geometry.encoding.encodePath( polyline.getPath() );
SaveMyPath(encodedpath);
});
google.maps.event.addListener(polyline.getPath(), 'insert_at', function () {
var encodedpath=google.maps.geometry.encoding.encodePath( polyline.getPath() );
SaveMyPath(encodedpath);
});
It's up to you to build the function SaveMyPath

How to add direction on tracking path for google maps

I am showing the tracking on map with marker points and line connecting them.
The problem is that i want to show the direction of travel on the links;
so I am not getting how to show the direction on the line between the marker points.
Is there any way to accomplish this task.
Showing the direction on the polyline can be accomplished with arrows.
There are some predefined paths that the google maps api3 provides.
See this section of the documentation -
SYMBOLS ON POLYLINE, that can be used other than an arrow.
Have a look at this fiddle that uses an arrow to indicate the direction on the polyline.
DEMO with a sigle symbol
You can also set the repeat property for the symbol so that it repeats for regular intervals.
DEMO with repeating symbols
JavaScript-
var iconsetngs = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
var polylineoptns = {
path: markers,
strokeOpacity: 0.8,
strokeWeight: 3,
map: map,
icons: [{
icon: iconsetngs,
offset: '100%'}]
};
polyline = new google.maps.Polyline(polylineoptns);
The interesting feature of this predefined symbol(the forward arrow specially) is that the arrow points towards the exact direction of which your co-ordinates are located. So, that obviously serves the purpose of denoting the direction in a Tracking System.
UPDATE: Not sure about the point you are trying to tell in the comments. The markers can be displayed the same way. Here is the code that adds markers with a loop and also set the polyline with arrows:
DEMO WITH MARKERS AND POLYLINE
Javascript:
var polylineoptns = {
strokeOpacity: 0.8,
strokeWeight: 3,
map: map,
icons: [{
repeat: '70px', //CHANGE THIS VALUE TO CHANGE THE DISTANCE BETWEEN ARROWS
icon: iconsetngs,
offset: '100%'}]
};
polyline = new google.maps.Polyline(polylineoptns);
var z = 0;
var path = [];
path[z] = polyline.getPath();
for (var i = 0; i < markers.length; i++) //LOOP TO DISPLAY THE MARKERS
{
var pos = markers[i];
var marker = new google.maps.Marker({
position: pos,
map: map
});
path[z].push(marker.getPosition()); //PUSH THE NEWLY CREATED MARKER'S POSITION TO THE PATH ARRAY
}