Draw airline flight map using Google Map APIs - google-maps-api-3

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>

Related

How to remove maplabel library and polygon in Google Map API

I'm using google maps API to allow the user draw polygons and display the length of every single border using maplabel library. But I have a problem when removing polygon and map label, I don't know how to remove them from Google Map.
My code looks like this:
HTML
<button id="enablePolygon">draw</button>
<button id="removePolygon">remove</button>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=drawing"></script>
<script src="https://cdn.jsdelivr.net/npm/js-map-label#1.0.1/src/maplabel.js"></script>
JS
var labels = [];
var allOverlays = [];
function setSelection(shape) {
selectedShape = shape;
shape.setEditable(true);
}
function initMap() {
var options = {
zoom: 14,
center: {
lat: 52.250618,
lng: 20.9774
}
};
var map = new google.maps.Map(document.getElementById("map"), options);
var drawingManager = new google.maps.drawing.DrawingManager({
polygonOptions: {
draggable: false,
fillColor: "#0e97fa",
fillOpacity: 0.2,
strokeWeight: 2,
strokeColor: "#0e97fa",
editable: true,
zIndex: 1
},
drawingControl: false,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes:
[
google.maps.drawing.OverlayType.POLYGON,
/* google.maps.drawing.OverlayType.POLYLINE, */
]
},
map: map,
drawingMode: 'polygon'
});
function attachPolygonInfoWindow(polygon) {
if (!polygon.labels) polygon.labels = [];
for (var i = 0; i < polygon.labels.length; i++) {
polygon.labels[i].setMap(null);
}
polygon.labels = [];
var path = polygon.getPath();
var points = path.getArray();
var area = google.maps.geometry.spherical
.computeArea(path.getArray())
.toFixed(0);
var bounds = new google.maps.LatLngBounds();
var i;
for (i = 0; i < points.length; i++) {
bounds.extend(points[i]);
}
var boundsCenter = bounds.getCenter();
var centerLabel = new MapLabel({
map: map,
position: boundsCenter,
fontSize: 14,
align: "center",
zIndex: 3
});
polygon.labels.push(centerLabel);
centerLabel.set("position", bounds.getCenter());
centerLabel.set("text", area + " m2");
if (path.getLength() < 2) return;
for (var i = 0; i < polygon.getPath().getLength(); i++) {
// for each side in path, compute center and length
var start = polygon.getPath().getAt(i);
var end = polygon.getPath().getAt(i < polygon.getPath().getLength() - 1 ? i + 1 : 0);
var sideLength = google.maps.geometry.spherical.computeDistanceBetween(start, end);
console.log(sideLength)
var sideCenter = google.maps.geometry.spherical.interpolate(start, end, 0.5);
/* console.log("sideCenter=" + sideCenter.toUrlValue(6)); */
var sideLabel = new MapLabel({
map: map,
fontSize: 14,
align: "center",
zIndex: 3
});
sideLabel.set("position", sideCenter);
sideLabel.set("text", sideLength.toFixed(2) + "m");
polygon.labels.push(sideLabel);
}
}
function removePolygonInfoWindow() {
for (var i = 0; i < labels.length; i++) {
labels[i].setMap(null);
}
labels = [];
}
google.maps.event.addListener(drawingManager, "overlaycomplete", function(e) {
allOverlays.push(e);
if (e.type != google.maps.drawing.OverlayType.MARKER) {
drawingManager.setDrawingMode(null);
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, "click", function() {
setSelection(newShape);
});
if (newShape.type == "polygon") {
var path = newShape.getPath();
google.maps.event.addListener(path, "insert_at", function() {
attachPolygonInfoWindow(newShape);
});
google.maps.event.addListener(path, "set_at", function() {
attachPolygonInfoWindow(newShape);
});
attachPolygonInfoWindow(newShape);
}
setSelection(newShape);
}
});
var enablePolygon = document.getElementById('enablePolygon');
enablePolygon.addEventListener('click', function(){
drawingManager.setMap(map);
drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
});
var removePolygon = document.getElementById('removePolygon');
removePolygon.addEventListener('click', function(){
selectedShape.setMap(null);
drawingManager.setMap(null);
centerLabel.setRemoveLabel(true);
});
}
initMap();
Here is demo
I get a javascript error with the posted code: Uncaught ReferenceError: centerLabel is not defined. Not sure why you are using that variable, you are saving the labels in a property of the polygons labels. To remove them, iterate through that array, calling .setMap(null) on each label.
removePolygon.addEventListener('click', function() {
selectedShape.setMap(null);
drawingManager.setMap(null);
for (var i = 0; i < selectedShape.labels.length; i++) {
selectedShape.labels[i].setMap(null);
}
});
updated fiddle
code snippet:
var labels = [];
var allOverlays = [];
function setSelection(shape) {
selectedShape = shape;
shape.setEditable(true);
}
function initMap() {
var options = {
zoom: 14,
center: {
lat: 52.250618,
lng: 20.9774
}
};
var map = new google.maps.Map(document.getElementById("map"), options);
var drawingManager = new google.maps.drawing.DrawingManager({
polygonOptions: {
draggable: false,
fillColor: "#0e97fa",
fillOpacity: 0.2,
strokeWeight: 2,
strokeColor: "#0e97fa",
editable: true,
zIndex: 1
},
drawingControl: false,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYGON,
/* google.maps.drawing.OverlayType.POLYLINE, */
]
},
map: map,
drawingMode: 'polygon'
});
function attachPolygonInfoWindow(polygon) {
if (!polygon.labels) polygon.labels = [];
for (var i = 0; i < polygon.labels.length; i++) {
polygon.labels[i].setMap(null);
}
polygon.labels = [];
var path = polygon.getPath();
var points = path.getArray();
var area = google.maps.geometry.spherical
.computeArea(path.getArray())
.toFixed(0);
var bounds = new google.maps.LatLngBounds();
var i;
for (i = 0; i < points.length; i++) {
bounds.extend(points[i]);
}
var boundsCenter = bounds.getCenter();
var centerLabel = new MapLabel({
map: map,
position: boundsCenter,
fontSize: 14,
align: "center",
zIndex: 3
});
polygon.labels.push(centerLabel);
centerLabel.set("position", bounds.getCenter());
centerLabel.set("text", area + " m2");
if (path.getLength() < 2) return;
for (var i = 0; i < polygon.getPath().getLength(); i++) {
// for each side in path, compute center and length
var start = polygon.getPath().getAt(i);
var end = polygon.getPath().getAt(i < polygon.getPath().getLength() - 1 ? i + 1 : 0);
var sideLength = google.maps.geometry.spherical.computeDistanceBetween(start, end);
console.log(sideLength)
var sideCenter = google.maps.geometry.spherical.interpolate(start, end, 0.5);
/* console.log("sideCenter=" + sideCenter.toUrlValue(6)); */
var sideLabel = new MapLabel({
map: map,
fontSize: 14,
align: "center",
zIndex: 3
});
sideLabel.set("position", sideCenter);
sideLabel.set("text", sideLength.toFixed(2) + "m");
polygon.labels.push(sideLabel);
}
}
function removePolygonInfoWindow() {
for (var i = 0; i < labels.length; i++) {
labels[i].setMap(null);
}
labels = [];
}
google.maps.event.addListener(drawingManager, "overlaycomplete", function(e) {
allOverlays.push(e);
if (e.type != google.maps.drawing.OverlayType.MARKER) {
drawingManager.setDrawingMode(null);
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, "click", function() {
setSelection(newShape);
});
if (newShape.type == "polygon") {
var path = newShape.getPath();
google.maps.event.addListener(path, "insert_at", function() {
attachPolygonInfoWindow(newShape);
});
google.maps.event.addListener(path, "set_at", function() {
attachPolygonInfoWindow(newShape);
});
attachPolygonInfoWindow(newShape);
}
setSelection(newShape);
}
});
var enablePolygon = document.getElementById('enablePolygon');
enablePolygon.addEventListener('click', function() {
drawingManager.setMap(map);
drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
});
var removePolygon = document.getElementById('resetPolygon');
removePolygon.addEventListener('click', function() {
selectedShape.setMap(null);
drawingManager.setMap(null);
for (var i = 0; i < selectedShape.labels.length; i++) {
selectedShape.labels[i].setMap(null);
}
});
}
initMap();
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<button id="enablePolygon">draw</button>
<button id="resetPolygon">remove</button>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=drawing"></script>
<script src="https://cdn.jsdelivr.net/npm/js-map-label#1.0.1/src/maplabel.js"></script>

Circles fill colour

I wonder it is any chance to fill different color between circles, so in the code below I have used code for cities but work for my purpose as well. Anyway I have 4 circles from the same center point, 4,6,8,11 miles and they are marked by strokecolor. However I wonder can I have different fill between 4-6, 6-8, 8-11 miles??
var distancemap = {
fourmiles: {
center: {lat: 53.3555367, lng: -6.2748774},
distance: 6437.38
},
sixmiles: {
center: {lat: 53.3555367, lng: -6.2748774},
distance: 9656.064
},
eightmiles: {
center: {lat: 53.3555367, lng: -6.2748774},
distance: 12874.8
},
elevenmiles: {
center: {lat: 53.3555367, lng: -6.2748774},
distance: 17702.8
}
};
function initAutocomplete() {
// Create the map.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 53.3555367, lng: -6.2748774},
mapTypeId: 'roadmap'
});
// Construct the circle for each value in distancemap.
// Note: We scale the area of the circle based on the distance.
for (var city in distancemap) {
// Add the circle for this city to the map.
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#000000',
fillOpacity: 0.005,
map: map,
center: distancemap[city].center,
radius: Math.abs(distancemap[city].distance) * 1
});
You can't make "holes" in a google.maps.Circle. But you can make circular google.maps.Polygons with holes in them. See this related question:
Draw ring (not circle) in Google Maps API
// Add the circle for this city to the map.
var paths;
if (i==0) {
// innermost circle, no "hole"
paths = [drawCircle(distanceArray[0].center, Math.abs(distanceArray[0].distance) * 1, 1)];
} else {
// every other circle has a "hole" the size of the inner/next smallest circle
paths = [
drawCircle(distanceArray[i-1].center, Math.abs(distanceArray[i-1].distance) * 1, -1),
drawCircle(distanceArray[i].center, Math.abs(distanceArray[i].distance) * 1, 1)
];
}
var cityCircle = new google.maps.Polygon({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: distanceArray[i].color,
fillOpacity: 0.5,
map: map,
paths: paths
});
proof of concept fiddle
code snippet:
function initAutocomplete() {
// Create the map.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: 53.3555367,
lng: -6.2748774
},
mapTypeId: 'roadmap'
});
for (var i = 0; i < distanceArray.length; i++) {
// Add the circle for this city to the map.
var paths;
if (i == 0) {
paths = [drawCircle(distanceArray[0].center, Math.abs(distanceArray[0].distance) * 1, 1)];
} else {
paths = [drawCircle(distanceArray[i - 1].center, Math.abs(distanceArray[i - 1].distance) * 1, -1),
drawCircle(distanceArray[i].center, Math.abs(distanceArray[i].distance) * 1, 1)
];
}
var cityCircle = new google.maps.Polygon({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: distanceArray[i].color,
fillOpacity: 0.5,
map: map,
paths: paths
});
}
}
google.maps.event.addDomListener(window, "load", initAutocomplete);
function drawCircle(point, radius, dir) {
if (typeof point.lat !== "function") {
point = new google.maps.LatLng(point.lat, point.lng);
}
var d2r = Math.PI / 180; // degrees to radians
var r2d = 180 / Math.PI; // radians to degrees
var earthsradius = 6378137.0; // 6378137.0 is the radius of the earth in meters
var points = 32;
// find the raidus in lat/lon
var rlat = (radius / earthsradius) * r2d;
var rlng = rlat / Math.cos(point.lat() * d2r);
var extp = new Array();
if (dir == 1) {
var start = 0;
var end = points + 1;
} // one extra here makes sure we connect the ends
else {
var start = points + 1;
var end = 0;
}
for (var i = start;
(dir == 1 ? i < end : i > end); i = i + dir) {
var theta = Math.PI * (i / (points / 2));
ey = point.lng() + (rlng * Math.cos(theta)); // center a + radius x * cos(theta)
ex = point.lat() + (rlat * Math.sin(theta)); // center b + radius y * sin(theta)
extp.push(new google.maps.LatLng(ex, ey));
// bounds.extend(extp[extp.length - 1]);
}
return extp;
}
var distancemap = {
fourmiles: {
center: {
lat: 53.3555367,
lng: -6.2748774
},
distance: 6437.38,
color: "#FF0000"
},
sixmiles: {
center: {
lat: 53.3555367,
lng: -6.2748774
},
distance: 9656.064,
color: "#00FF00"
},
eightmiles: {
center: {
lat: 53.3555367,
lng: -6.2748774
},
distance: 12874.8,
color: "#0000FF"
},
elevenmiles: {
center: {
lat: 53.3555367,
lng: -6.2748774
},
distance: 17702.8,
color: "#FFFF00"
}
};
var distanceArray = [
distancemap.fourmiles,
distancemap.sixmiles,
distancemap.eightmiles,
distancemap.elevenmiles
]
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map"></div>

Cannot get my polyline drawn or visible

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

Google Maps getBounds() returns undefined

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

Center map and zoom to fit the markers on the screen

I have the following code to detect the visitors GPS position and show it on the Google Maps JavaScript v3 map. Everything works as I want it but the code will not center or zoom as I want - it simple use the standard position (right over Asia)! I want it to fit the markers on the map.
var rendererOptions = {
draggable: false
};
if(navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.watchPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
} else {
alert('Din webbläsare stödjer inte någon geologisk lokalisering med hjälp av HTML5');
}
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var marker_gps;
var map_gps;
var options_gps;
function displayPosition(position) {
/***********************
** GPS-POSITION **
************************/
directionsDisplay = new google.maps.DirectionsRenderer();
localStorage.coor = position.coords.latitude.toFixed(6) + ',' + position.coords.longitude.toFixed(6);
var gps_coor = new google.maps.LatLng(position.coords.latitude.toFixed(6), position.coords.longitude.toFixed(6));
if(typeof(marker) != 'undefined') marker.setMap(null);
localStorage.accuracy = position.coords.accuracy;
document.getElementById('accuracy').innerHTML = number_format(localStorage.accuracy) + ' meter';
directionsDisplay.setMap(map_gps);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
marker_gps = new google.maps.Marker({
position: gps_coor,
draggable: false,
map: map_gps
});
var circle_gps = new google.maps.Circle({
center: gps_coor,
radius: position.coords.accuracy,
map: map_gps,
fillColor: '#3333ff',
fillOpacity: 0.2,
strokeColor: '#3333ff',
strokeOpacity: 0.5,
strokeWeight: 1
});
/*****************************
** FÄRDSÄTT (DISTANS) **
******************************/
var start = new google.maps.LatLng(position.coords.latitude.toFixed(6), position.coords.longitude.toFixed(6));
var stop = new google.maps.LatLng(<?php echo $photo['coordinates_latitude'].','.$photo['coordinates_longitude']; ?>);
var request = {
origin: start,
destination: stop,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if(status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
directionsService.route(request, function(response, status) {
if(status == google.maps.DirectionsStatus.OK) {
var distance = (response.routes[0].legs[0].distance.value / 1000).toFixed(0);
var duration = secondsToString(response.routes[0].legs[0].duration.value);
document.getElementById('distance').innerHTML = 'Cirka ' + distance + ' kilometer';
document.getElementById('duration').innerHTML = 'Cirka ' + duration;
directionsDisplay.setDirections(response);
}
});
}
function initialize_gps() {
var coor = new google.maps.LatLng(localStorage.coor);
var bounds = new google.maps.LatLngBounds();
options_gps = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: google.maps.LatLng(localStorage.coor),
streetViewControl: false
}
map_gps = new google.maps.Map(document.getElementById('map-distance'), options_gps);
map_gps.fitBounds(bounds);
}
function secondsToString(seconds) {
var numdays = Math.floor(seconds / 86400);
var numhours = Math.floor((seconds % 86400) / 3600);
var numminutes = Math.floor(((seconds % 86400) % 3600) / 60);
return (numdays != 0 ? (numdays == 1 ? '1 dag' : numdays + ' dagar') + ', ' : '')
+ (numhours != 0 ? (numhours == 1 ? '1 timme' : numhours + ' timmar') + (numdays != 0 ? ', ' : ' och ') : '')
+ (numminutes != 0 ? (numminutes == 1 ? '1 minut' : numminutes + ' minuter') : '');
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert('Error: ' + errors[error.code]);
}
How can I make this to work?
Thanks in advance.
EDIT
Here's the edited part of the initialize_gps function. This part didn't work - nothing new happened. It just center the map over Asia like before.
function initialize_gps() {
var coor = new google.maps.LatLng(localStorage.coor);
var bounds = new google.maps.LatLngBounds();
options_gps = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: google.maps.LatLng(localStorage.coor),
streetViewControl: false
}
map_gps = new google.maps.Map(document.getElementById('map-distance'), options_gps);
map_gps.fitBounds(bounds);
}
EDIT
I have copy-pasted the whole code to jsFiddle. Link: http://jsfiddle.net/edgren/WRxt4/
The general solution to fitting the map display to a set of markers is to add them to an empty google.maps.LatLngBounds object (by calling bounds.extend), then calling map.fitBounds with that bounds.
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
// Adds markers to the map.
for (let i = 0; i < beaches.length; i++) {
const beach = beaches[i];
var marker = new google.maps.Marker({
position: { lat: beach[1], lng: beach[2] },
map,
title: beach[0],
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
// to the base of the flagpole.
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 10,
center: { lat: 0, lng: 0 },
});
setMarkers(map);
}
// Data for the markers consisting of a name, a LatLng and a zIndex for the
// order in which these markers should display on top of each other.
const beaches = [
["Bondi Beach", -33.890542, 151.274856, 4],
["Coogee Beach", -33.923036, 151.259052, 5],
["Cronulla Beach", -34.028249, 151.157507, 3],
["Manly Beach", -33.80010128657071, 151.28747820854187, 2],
["Maroubra Beach", -33.950198, 151.259302, 1],
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
// Adds markers to the map.
for (let i = 0; i < beaches.length; i++) {
const beach = beaches[i];
var marker = new google.maps.Marker({
position: { lat: beach[1], lng: beach[2] },
map,
title: beach[0],
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Complex Marker Icons</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly"
async
></script>
</body>
</html>

Resources