I'm writing a code which will:
-- Load a map and center it on a KML
-- Draw a polygon based on the bounds of the map.
Here below the code. I get an error
Uncaught TypeError: Cannot call method 'getNorthEast' of undefined
function initialize()
{
var mapOptions =
{
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP //higer zoom
};
var KML1 = new google.maps.KmlLayer(
{
clickable: false,
url: 'https://s3.amazonaws.com/navizon.its.fp/1001/f43l9uvts1_a.kml' //kml link for the floor-plan
});
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
KML1.setMap(map);
var bounds = new google.maps.LatLngBounds();
bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var QLat = Math.abs((ne.lat()-sw.lat())/5);
var QLng = Math.abs((sw.lng()-ne.lng())/5);
var swLat = sw.lat()+QLat;
var swLng = sw.lng()+QLng;
var neLat = ne.lat()-QLat;
var neLng = ne.lng()-QLng;
ne = new google.maps.LatLng(neLat,neLng);
sw = new google.maps.LatLng(swLat,swLng);
var Coords = [
ne, new google.maps.LatLng(ne.lat(), sw.lng()),
sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
];
surface = new google.maps.Polygon(
{
paths: Coords,
strokeColor: '#00AAFF',
strokeOpacity: 0.6,
strokeWeight: 2,
fillColor: '#00CC66',
fillOpacity: 0.15,
editable: true,
draggable: true,
geodesic:true
});
surface.setMap(map);
google.maps.event.addListener(surface, 'mousemove', ciao) //add listener for changes
//$("#results").append(coordinates[0]);
//Let's update area and price as the poly changes
function ciao(event)
{
var vertices = this.getPath();
// Iterate over the vertices.
for (var i =0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
Coords = []
Coords.push(xy);
};
}
}
Any Suggestion?
Thanks,
Daniele
You need to put all the code that depends on the map bounds inside the event listener.
var surface = null;
function initialize()
{
var mapOptions =
{
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP //higer zoom
};
var KML1 = new google.maps.KmlLayer(
{
clickable: false,
url: 'https://s3.amazonaws.com/navizon.its.fp/1001/f43l9uvts1_a.kml' //kml link for the floor-plan
});
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
KML1.setMap(map);
google.maps.event.addListener(map,'bounds_changed', function()
{
var bounds = new google.maps.LatLngBounds();
bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var QLat = Math.abs((ne.lat()-sw.lat())/5);
var QLng = Math.abs((sw.lng()-ne.lng())/5);
var swLat = sw.lat()+QLat;
var swLng = sw.lng()+QLng;
var neLat = ne.lat()-QLat;
var neLng = ne.lng()-QLng;
ne = new google.maps.LatLng(neLat,neLng);
sw = new google.maps.LatLng(swLat,swLng);
var Coords = [
ne, new google.maps.LatLng(ne.lat(), sw.lng()),
sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
];
surface = new google.maps.Polygon(
{
paths: Coords,
strokeColor: '#00AAFF',
strokeOpacity: 0.6,
strokeWeight: 2,
fillColor: '#00CC66',
fillOpacity: 0.15,
editable: true,
draggable: true,
geodesic:true
});
surface.setMap(map);
}); // end of listener callbck
google.maps.event.addListener(surface, 'mousemove', ciao) //add listener for changes
//$("#results").append(coordinates[0]);
//Let's update area and price as the poly changes
function ciao(event)
{
var vertices = this.getPath();
// Iterate over the vertices.
for (var i =0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
Coords = []
Coords.push(xy);
};
}
} // end of initialize
Related
I use this function to draw my route between A and Z via the Waypoints array.
Is it possible to change the line color (default blue) but just between certain waypoints ?
I mean i want blue between A and B, red between C and D, ....
I found how to change the color of the line
var directionsDisplay = new google.maps.DirectionsRenderer({polylineOptions: { strokeColor: "#8b0013" },
but i can't find how to do it in waypoints...?
thanks for your help
function calcRoute(origin_lat,origin_lng,destination_lat,destination_lng) {
console.log ("Entrée CALC ROUTE");
var origin = new google.maps.LatLng(origin_lat,origin_lng);
var destination = new google.maps.LatLng(destination_lat,destination_lng);
var waypointsArray = document.getElementById('waypoints').value.split("|");
var waypts = [];
for (i = 0; i < waypointsArray.length; i++) {
if (waypointsArray[i]!="") {
var waypoint = waypointsArray[i];
var waypointArray = waypoint.split(",");
var waypointLat = waypointArray[0];
var waypointLng = waypointArray[1];
console.log("waypts lat " + waypointLat);
console.log("waypts lng " + waypointLng);
waypts.push({
location: new google.maps.LatLng(waypointLat,waypointLng),
stopover: true
})
}
}
console.log("waypts " + waypts.length);
var request = {
origin:origin,
destination:destination,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: waypts,
provideRouteAlternatives: true
};
console.log ("Calc request "+JSON.stringify(request));
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
You can't modify just a single segment of the output of the DirectionsRenderer. You can either render each segment with a separate DirectionsRenderer or create your own custom renderer that allows you to create individual polylines for each step of the route and color each one independently.
proof of concept fiddle with a custom renderer
code snippet:
var map;
var directionsService;
var directionsDisplay;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
suppressPolylines: true
});
// Baltimore, MD, USA (39.2903848, -76.61218930000001)
// Boston, MA, USA (42.3600825, -71.05888010000001)
// Philadelphia, PA, USA (39.9525839, -75.16522150000003)
// New York, NY, USA (40.7127837, -74.00594130000002)
calcRoute(39.2903848, -76.6121893, 42.3600825, -71.05888);
}
google.maps.event.addDomListener(window, "load", initialize);
function calcRoute(origin_lat, origin_lng, destination_lat, destination_lng) {
console.log("Entrée CALC ROUTE");
var origin = new google.maps.LatLng(origin_lat, origin_lng);
var destination = new google.maps.LatLng(destination_lat, destination_lng);
var waypointsArray = document.getElementById('waypoints').value.split("|");
var waypts = [];
for (i = 0; i < waypointsArray.length; i++) {
if (waypointsArray[i] != "") {
var waypoint = waypointsArray[i];
var waypointArray = waypoint.split(",");
var waypointLat = waypointArray[0];
var waypointLng = waypointArray[1];
console.log("waypts lat " + waypointLat);
console.log("waypts lng " + waypointLng);
waypts.push({
location: new google.maps.LatLng(waypointLat, waypointLng),
stopover: true
})
}
}
console.log("waypts " + waypts.length);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: waypts,
provideRouteAlternatives: true
};
console.log("Calc request " + JSON.stringify(request));
directionsService.route(request, customDirectionsRenderer);
}
function customDirectionsRenderer(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var polyline = new google.maps.Polyline({
map: map,
strokeColor: "blue",
path: []
})
if (i == 1) {
polyline.setOptions({
strokeColor: "red"
});
}
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
}
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="waypoints" value="39.9525839,-75.1652215|40.7127837,-74.0059413" />
<div id="map_canvas"></div>
I am trying to draw an airline flight map using Google Map APIs. But I got some issues in generating polylines between every two points. So far, it only returns one polyline of the very first two points. I could not find any error so far. Is there anything wrong with the last for loop? Any comments and help will be highly appreciated!
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: 41.871314, lng: -99.869580},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var Lat = [42.365843,37.756066,47.450431,28.431450,38.898793,34.040667];
var Lng = [-71.009625,-122.440175,-122.308806,-81.308094,-77.037227,-118.289537];
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
var Poly = new Array();
for (var i = 0; i<Lat.length; i++) {
var pos = new google.maps.LatLng(Lat[i],Lng[i]);
Poly.push(pos);
};
for (var j = 0; j<Poly.length; j++) {
if (j%2 == 0){
var poly = new Array();
poly = Poly.slice(j,j+2);
var flowline = new google.maps.Polyline({
path: poly,
geodesic: true,
strokeColor: "#DC143C",
strokeOpacity: .8,
strokeWeight: 2,
icons: [{
icon: lineSymbol,
offset: '100%'
}],
});
}
};
flowline.setMap(map);
}
You are only setting the map property of the last polyline. This is outside of the loop that creates the polylines:
flowline.setMap(map);
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 41.871314,
lng: -99.869580
},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var Poly = new Array();
for (var i = 0; i < Lat.length; i++) {
var pos = new google.maps.LatLng(Lat[i], Lng[i]);
Poly.push(pos);
}
var flowlineNonGeodesic = new google.maps.Polyline({
path: Poly,
geodesic: false,
strokeColor: "#00FF00",
strokeOpacity: .8,
strokeWeight: 2,
map: map
});
for (var j = 0; j < Poly.length; j++) {
if (j % 2 == 0) {
var poly = Poly.slice(j, j + 2);
var flowline = new google.maps.Polyline({
path: poly,
geodesic: true,
strokeColor: "#DC143C",
strokeOpacity: .8,
strokeWeight: 2,
icons: [{
icon: lineSymbol,
offset: '100%'
}],
});
flowline.setMap(map);
}
}
}
google.maps.event.addDomListener(window, "load", initMap);
var Lat = [42.365843, 37.756066, 47.450431, 28.431450, 38.898793, 34.040667];
var Lng = [-71.009625, -122.440175, -122.308806, -81.308094, -77.037227, -118.289537];
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
I try to draw a polyline according to this example:
https://developers.google.com/maps/documentation/javascript/examples/geometry-encodings.
My map is displayed, markers are displayed as well but the polyline is not drawn, or not visible.
I don't see what's wrong.
My javascript is:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=geometry"></script>
$( document ).ready(function($) {
var map;
var poly;
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var ndgIconBase = 'http://example.com/img/';
var clickMarker;
nextWaypoint = parseInt(document.getElementById('agpoiwaypoints_size').innerHTML, 10);
countWaypoint = nextWaypoint;
function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var content;
content = document.getElementById('agpoi-0-lat').innerHTML
var lat0 = parseFloat(content.substr(content.indexOf(":")+1));
content = document.getElementById('agpoi-0-lng').innerHTML
var lng0 = parseFloat(content.substr(content.indexOf(":")+1));
content = document.getElementById('agpoi-1-lat').innerHTML
var lat1 = parseFloat(content.substr(content.indexOf(":")+1));
content = document.getElementById('agpoi-1-lng').innerHTML
var lng1 = parseFloat(content.substr(content.indexOf(":")+1));
var mapOptions = {
center: new google.maps.LatLng((lat1 + lat0) / 2, (lng1 + lng0) / 2),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3,
map: map
};
poly = new google.maps.Polyline(polyOptions);
new google.maps.Marker({
position: {lat: lat0, lng: lng0},
map: map,
icon: ndgIconBase + 'myLogo.png'
});
new google.maps.Marker({
position: {lat: lat1, lng: lng1},
map: map,
icon: ndgIconBase + 'myLogo.png'
});
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
var position = {lat: lat0, lng: lng0};
var path = poly.getPath();
path.push(position);
var content;
for (i = 0; i < countWaypoint; i++) {
content = document.getElementById("agpoiwaypoints-" + i + "-latitude").value;
lat = parseFloat(content);
content = document.getElementById("agpoiwaypoints-" + i + "-longitude").value;
lng = parseFloat(content);
position = {lat: lat, lng: lng};
new google.maps.Marker({
position: position,
map: map
});
path = poly.getPath();
path.push(position);
}
position = {lat: lat1, lng: lng1};
path = poly.getPath();
path.push(position);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, 'click', placeMarker);
function placeMarker(position, map) {
if (clickMarker == 0) {
clickMarker = new google.maps.Marker({
position: position,
map: map
});
} else {
clickMarker.setPosition( position );
}
}
$("body").on("click", ".remove_agpoiwaypoint", function (e) {
e.preventDefault();
});
$("body").on("click", ".add_agpoiwaypoint", function (e) {
e.preventDefault();
var path = poly.getPath();
var position = clickMarker.getPosition();
path.push(position);
});
});
When you do path = poly.getPath(); you're simply getting an array and assigning it to a variable called path. Then when you do path.push(position); you're merely adding things into that variable... it's not updating the polyline's path.
Instead you then need to update the polyline too, e.g. then you could also do
poly.setPath(path);
I have a bounds to a place and created a polygon of that place.
How can I generate a random point inside the bounds of that polygon?
One way of doing it. This will calculate the bounds of the polygon, then guess a random point inside that bounds, if the point is contained by the polygon, it will put a marker there.
// calculate the bounds of the polygon
var bounds = new google.maps.LatLngBounds();
for (var i=0; i < polygon.getPath().getLength(); i++) {
bounds.extend(polygon.getPath().getAt(i));
}
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
// Guess 100 random points inside the bounds,
// put a marker at the first one contained by the polygon and break out of the loop
for (var i = 0; i < 100; i++) {
var ptLat = Math.random() * (ne.lat() - sw.lat()) + sw.lat();
var ptLng = Math.random() * (ne.lng() - sw.lng()) + sw.lng();
var point = new google.maps.LatLng(ptLat,ptLng);
if (google.maps.geometry.poly.containsLocation(point,polygon)) {
var marker = new google.maps.Marker({position:point, map:map});
break;
}
}
working fiddle
working fiddle with up to 100 random points
var polygon;
function initialize() {
var map = new google.maps.Map(document.getElementById("map"),
{
zoom: 4,
center: new google.maps.LatLng(22.7964, 79.8456),
mapTypeId: google.maps.MapTypeId.HYBRID
});
var coords =
[
new google.maps.LatLng(18.979026,72.949219), //Mumbai
new google.maps.LatLng(28.613459,77.255859), //Delhi
new google.maps.LatLng(22.512557,88.417969), //Kolkata
new google.maps.LatLng(12.940322,77.607422) //Bengaluru
];
polygon = new google.maps.Polygon({
paths: coords,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.26
});
polygon.setMap(map);
var bounds = new google.maps.LatLngBounds();
for (var i=0; i < polygon.getPath().getLength(); i++) {
bounds.extend(polygon.getPath().getAt(i));
}
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
for (var i = 0; i < 100; i++) {
var ptLat = Math.random() * (ne.lat() - sw.lat()) + sw.lat();
var ptLng = Math.random() * (ne.lng() - sw.lng()) + sw.lng();
var point = new google.maps.LatLng(ptLat,ptLng);
if (google.maps.geometry.poly.containsLocation(point,polygon)) {
var marker = new google.maps.Marker({position:point, map:map});
var infowindow = new google.maps.InfoWindow({});
google.maps.event.addListener(marker, "click", function(evt) {
infowindow.setContent(marker.getPosition().toUrlValue(6));
infowindow.open(map, marker);
});
break;
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map" style="width: 530px; height: 500px">
</div>
Hi I have a map that shows direction of shuttle following are the map and direction initialisation code
var centerLatlng = new google.maps.LatLng(-34.942799,138.553365);
var myOptions = {
zoom: 13,
center: centerLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
panControl:true,
streetViewControl: false,
OverviewMapControlOptions:
{
opened: true
}
};
var map = new google.maps.Map(document.getElementById("map-guide-google-map"), myOptions);
Following is the Display Direction
function DisplayDirection(directionList){
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
markerOptions: {
visible:false
}
});
directionsDisplay.setMap(map);
//Request 0
var increaseSize = 7;
var index =0;
var theoryCurrentEndIndex = index + increaseSize;
var maxmimumIndex = directionList.length-1;
var origin = directionList[index];
var destination = theoryCurrentEndIndex < maxmimumIndex?directionList[theoryCurrentEndIndex]:directionList[maxmimumIndex];
var actualCurrentEndIndex = theoryCurrentEndIndex < maxmimumIndex?theoryCurrentEndIndex: maxmimumIndex;
var waypoints = new Array();
if(actualCurrentEndIndex-index>1) {
for(var i=index+1;i<actualCurrentEndIndex;i++) {
waypoints.push(
{
location:directionList[i],
stopover:true}
);
}
}
var request = {
origin: origin,
destination: destination,
waypoints : waypoints,
provideRouteAlternatives:false,
travelMode: google.maps.TravelMode.WALKING,
unitSystem: google.maps.UnitSystem.METRIC
}
directionsService.route(request, function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
}) ;
}
How can I reset the LatLongBounds to show all the stop points and centre the map