Draw route on Google Maps taking coordinates from a database - google-maps

Below is a map to demonstrate the type of output I would like to achieve.
However, when I fetch the coordinates from the database I don't know how to draw them on Google Maps in order to get this type of output. I use this code but I don't how to put coordinates in this code from the database.
var MapPoints = '[{"address":{"address":"plac Grzybowski, Warszawa, Polska","lat":"52.2360592","lng":"21.002903599999968"},"title":"Warszawa"},{"address":{"address":"Jana Paw\u0142a II, Warszawa, Polska","lat":"52.2179967","lng":"21.222655600000053"},"title":"Wroc\u0142aw"},{"address":{"address":"Wawelska, Warszawa, Polska","lat":"52.2166692","lng":"20.993677599999955"},"title":"O\u015bwi\u0119cim"}]';
var MY_MAPTYPE_ID = 'custom_style';
function initialize() {
if (jQuery('#map').length > 0) {
var locations = jQuery.parseJSON(MapPoints);
window.map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
var infowindow = new google.maps.InfoWindow();
var flightPlanCoordinates = [];
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
map: map
});
flightPlanCoordinates.push(marker.getPosition());
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i]['title']);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
var flightPath = new google.maps.Polyline({
map: map,
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);

You're adding markers to the map so you can extract their coordinates to make a polyline. You can cut out the middleman and use the LatLngs to make the polyline.
$('document').ready(function() {
initialize();
});
// You don't need google.maps.event.addDomListener(window, 'load', initialize);
// if you use jQuery's $(document).ready() function.
function initialize() {
var flightPathCoordinates = [];
// Get the data from the server.
$.get(
"url/of/serverScript.php", // Wherever you're getting your var MapPoints JSON.
function(response) {
var locations = $.parseJSON(response);
var coordinatePair;
for (i = 0; i < locations.length; i++) {
coordinatePair = new google.maps.LatLng(locations[i].address.lat,
locations[i].address.lng);
flightPathCoordinates.push(coordinatePair);
}
}); // end $.get()
// Create the map.
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
});
// Create the polyline.
var flightPath = new google.maps.Polyline({
map: map,
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
// Add it to the map.
flightPath.setMap(map);
}
Note: You can use $ instead of jQuery. e.g. these are equivalent: jQuery('#map') $('#map')

Related

map does not display without domlistner

i want to draw a polygon on the trigger of certain function. i have created a button submit which initiate the insert function which got coordinates from the user and call display function.
var map; var triangleCoords = [];
function insert() {
//var markerImage = 'assets/img/marker.png';
// var marker = new google.maps.Marker({
// position: location,
// map: map,
// icon: markerImage
// });
triangleCoords = [
[30.983611, 73.332778],
[30.93361111, 73.33055556],
[30.93361111, 73.43055556],
[30.98111111, 73.42944444]
];
display();
}
function display()
{
function initMap() {
var location = new google.maps.LatLng(31.1704, 72.7097);
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: location,
zoom: 7,
panControl: false
// mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
var points = [];
for (var i = 0; i < triangleCoords.length; i++) {
points.push({
lat: triangleCoords[i][0],
lng: triangleCoords[i][1]
});
}
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: points,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
zoom: 13,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
}
google.maps.event.addDomListener(window,'load',initMap);
}
code is working fine but if i remove google.maps.event.addDomListener(window,'load',initMap); line map doesnot display. my submit button clears the forms.

Google maps v3 decode polygon(s) from MySQL database

I would like to draw one or more polygons which are saved encoded in the MySQL database. I've based my code on the known bermudatriangle script example. The XML from "polygon_xml.php" is OK. For now, there's only 1 encoded coordinate in the database. At: //alert1(decodedPolygon); the coordinates are shown, but at //alert2(decodedPolygon); it's not. It has something to do with the array decodedPolygon I guess. What makes me more confusing is that the polygon does show when I uncomment //alert2(decodedPolygon);. Alert2 is empty but after clicking "OK", the polygon is shown on the map!??? Finally I would like to add text to the XML and place it in the infowindow instead of the coordinates.
My 3 encoded coordinates are:
{zzfIsjmu#kHuczRrg{NxcsO}t{GtczR
a}~cIqcskBu|sEov{OoxNel}AfccMwfzG~q|#nknX}u~GvczR
cljkHmfoQl|J{hrV~syGzhrV
I hope somebody can help / explain.
Here's my code so far:
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry">
<script>
var map;
var infoWindow;
var decodedPolygon = [];
function initialize() {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(49.724479, 17.578125),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
downloadUrl("polygon_xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var encodedPath = markers[i].getAttribute("coords");
decodedPolygon = google.maps.geometry.encoding.decodePath(encodedPath);
//alert1(decodedPolygon);
//bounds.extend(decodedPolygon);
}
})
//alert2(decodedPolygon);
// Construct the polygon.
bermudaTriangle = new google.maps.Polygon({
paths: decodedPolygon,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
// Add a listener for the click event.
google.maps.event.addListener(bermudaTriangle, 'click', showArrays);
infoWindow = new google.maps.InfoWindow();
}
/** #this {google.maps.Polygon} */
function showArrays(event) {
// Since this polygon has only one path, we can call getPath()
// to return the MVCArray of LatLngs.
var vertices = this.getPath();
var contentString = '<b>Bermuda Triangle polygon</b><br>' +
'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
'<br>';
// Iterate over the vertices.
for (var i = 0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' +
xy.lng();
}
// Replace the info window's content and position.
infoWindow.setContent(contentString);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div id="map-canvas"></div>
downloadUrl is asynchronous, you need to use the data returned inside the callback routine. Right now, the bermudaTriangle polygon is constructed before the data is returned (outside of the callback function).
function initialize() {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(49.724479, 17.578125),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
downloadUrl("polygon_xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var encodedPath = markers[i].getAttribute("coords");
var decodedPolygon = google.maps.geometry.encoding.decodePath(encodedPath);
for (var j = 0; j < decodedPolygon.length; j++) {
bounds.extend(decodedPolygon[j]);
}
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: decodedPolygon,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
// Add a listener for the click event.
google.maps.event.addListener(bermudaTriangle, 'click', showArrays);
}
map.fitBounds(bounds);
})
infoWindow = new google.maps.InfoWindow();
}
proof of concept fiddle

getJSON google maps Polyline

This is an example from my jsonData:
"lineformap":"new google.maps.LatLng(52.25602231800669, 6.160540580749512),new google.maps.LatLng(52.25543780780041, 6.1602723598480225),new google.maps.LatLng(52.255818725438296, 6.160014867782593)"
and this is my code:
(no line appears)
When i copy the data in to the code the lines are visable on the map
Who can help me with this
var poly;
var map;
function initialize() {
var latlng = new google.maps.LatLng(52.2554, 6.1627);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var bermudaTriangle;
map = new google.maps.Map(document.getElementById("ObjectMap"), myOptions);
$.getJSON('/api/dbklineforbws', function (createbws) {
$(createbws).each(function (i, itemb) {
// Define the LatLng coordinates for the polygon's path.
var flightPlanCoordinates = [
itemb.lineformap
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
For me it's very strange usage of json file. But, to make it work I'd change json file to:
{
"lineformap": "[new google.maps.LatLng(52.25602231800669, 6.160540580749512),new google.maps.LatLng(52.25543780780041, 6.1602723598480225),new google.maps.LatLng(52.255818725438296, 6.160014867782593)]"
}
and
var flightPlanCoordinates = [
itemb.lineformap
];
to
var flightPlanCoordinates = eval(itemb.lineformap);
to get polyline.

Google Map Polyline Arrays

I am new at Google Map applications. I have read an article about Polyline Arrays (https://developers.google.com/maps/documentation/javascript/overlays#PolylineArrays). In the example, it created a dynamic arrays using Event Click. My question is, is it possible that i can create a polyline in an array variable not on a click event?
Here is the code from google documentation:
var poly;
var map;
function initialize() {
var chicago = new google.maps.LatLng(41.879535, -87.624333);
var mapOptions = {
zoom: 7,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
// Add a listener for the click event
google.maps.event.addListener(map, 'click', addLatLng);
}
/**
* Handles click events on a map, and adds a new point to the Polyline.
* #param {MouseEvent} mouseEvent
*/
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
}
I have made some of my own code:
<script>
var line;
var map;
function initialize() {
var mapDiv = document.getElementById('map-canvas');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(0, -180),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var path = [new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856)];
line = new google.maps.Polyline({
path: path,
strokeColor: '#ff0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
line.setMap(map)
}
function addNewPoint(position) {
var path = line.getPath();
path.push(position);
}
''''' I create a single variable for a new path.
var NewPath = [new google.maps.LatLng(-27.46758, 153.027892)];
addNewPoint(NewPath);
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And when i run it. It does not work. Thank you for any response.
I think you need to change this:
var NewPath = [new google.maps.LatLng(-27.46758, 153.027892)];
addNewPoint(NewPath);
to this:
var NewPath = new google.maps.LatLng(-27.46758, 153.027892);
addNewPoint(NewPath);
So you only pass through a LatLng point, rather than an array containing one. So it corresponds more closely to the example you gave,
path.push(event.latLng);

I fail to put fillOpacity and strokeOpacity to work in the Google Maps API

I use the Google API to plot markers and a polygon. This works well, but I can't seem to get the polygon's fillOpacity and strokeOpacity working. It works when it is set to 0 or 1, which makes me believe that there is some kind of parsing error.
(I left the details out of the code below and just replaced it with example)
<script type="text/javascript">
var locations = [
['EXAMPLETEXT, EXAMPLECOORDINATE1, EXAMPLECOORDINATE2, 1],
];
var limburgcoordinaten = [
new google.maps.LatLng(EXAMPLECOORDINATE1, EXAMPLECOORDINATE2),
new google.maps.LatLng(EXAMPLECOORDINATE1, EXAMPLECOORDINATE2),
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: new google.maps.LatLng(EXAMPLECOORDINATE1, EXAMPLECOORDINATE2),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
var limburg = new google.maps.Polygon({
paths: limburgcoordinaten,
strokeColor: "#FF0000",
strokeOpacity: 0.7,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.3,
map: map
});
}
I hope that i'm just looking over something very obvious!