Cannot get my polyline drawn or visible - google-maps-api-3

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

Related

Draw airline flight map using Google Map APIs

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>

show infowindow has ID on Googlemaps by URL parameter

This js code is for showing customized Google Maps. I want to add function to this code. URL parameter as ID and show infowindow has this ID on Google Maps. For example "http://www.tabikobo.com/newyork/map/uptown/?=2962"(this ID is 2966).ID is loaded as 'id' in XMLdata.
var uptownMap,defLng = -73.963245,defLat = 40.779438,
san ={
init :
function(){
$(document).ready(function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=san.putGmap";
document.body.appendChild(script);
});
},
putGmap :
function(){
var myLatlng = new google.maps.LatLng(defLat, defLng);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
uptownMap = new google.maps.Map(document.getElementById("gmapArea"), myOptions);
san.getXmlData();
},
getXmlData : function(){
$.ajax({
type: 'GET',
cache: true,
async: true,
url: '/newyork/map_uptown_xml/',
datatype: 'xml',
success: san.parseXmlData
});
},
parseXmlData: function (xml) {
//a single infowindow for all markers
var infowindow = new google.maps.InfoWindow({
pixelOffset: new google.maps.Size(0, 10)
});
var i = 0,
id, name, url, lat, lng, copy, lead, ename, tag;
$("<ol/>")
.attr('id', 'gmapAnchor')
.appendTo('div#gmapController');
$(xml)
.find('item')
.each(function (i) {
i++;
id = $(this)
.find('description id')
.text();
name = $(this)
.find('description name')
.text();
url = $(this)
.find('description path')
.text();
lat = $(this)
.find('description lat')
.text();
lng = $(this)
.find('description lng')
.text();
tag = $(this)
.find('description tag')
.text();
tag = tag.slice(5, 20);
console.log(tag)
var customIcons = {
hotel:
{
icon: 'http://www.tabikobo.com/newyork/img/icon_hotel.png'
},
var icon = customIcons[tag] || {};
var myLatLng = new google.maps.LatLng(lat, lng);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: uptownMap,
icon: icon.icon,
});
var htmlTmpl = {
hotel:
{
content: '<div class="infoWinWrapper"><strong><a href="' +
url + '">' + name +
'</a></strong><br />' + ename +
'<br />' + lead + '</div>'
},
};
var htmlTmpl = htmlTmpl[tag] || {};
//click-listener for marker
google.maps.event.addListener(beachMarker, 'click',
function () {
//update the content
infowindow.setContent(
'<div class="hook">' + htmlTmpl
.content + '</div>');
infowindow.open(uptownMap, this);
google.maps.event.addListenerOnce(
infowindow, 'domready',
function () {
var l = $('.hook')
.parent()
.parent()
.parent()
.siblings()
.addClass("infoBox");
});
});
//Creat a Tag
san.putData(name, url, lat, lng, i);
});
},
putData : function(name, url, lat, lng, num){
var x = num;
x += '';
if(x.length == 1){
var y = '0' + x;
}else {
y = x;
}
san.setEvent();
},
setEvent : function(){
$("ul#area_list li a").bind('mouseover', function(){
$(this).parent().find('span.lat').text();
var point = new google.maps.LatLng(
$(this).parent().find('span.lat').text(),
$(this).parent().find('span.lng').text()
);
uptownMap.setZoom(17);
uptownMap.setCenter(point);
});
$("#btnResetZoom a").bind('click', function(){
var point = new google.maps.LatLng(defLat, defLng);
uptownMap.setZoom(15);
uptownMap.setCenter(point);
return false;
});
}
}
window.onload = san.init();
I solived myself! thanks.
var PageMapID = location.href.split('?=');
var PageMapID2 = PageMapID[PageMapID.length -1];
if (id == PageMapID2) {
$(document).ready(function(){
infowindow.open(uptownMap,beachMarker);
infowindow.setContent('<div class="hook">' + htmlTmpl.content + '</div>');
var latlng = new google.maps.LatLng(lat, lng);
uptownMap.setCenter(latlng);
});
}

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>

Geocoding using Google Maps API v3?

At the moment I use a latlang to specify the location:
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(52.097303, 0.275820);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var contentString = '<div id="bubbleContent">'+'<img src="images/logo.png" alt="logo" width="200" height="35"/>'
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
});
infowindow.open(map,marker);
}
</script>
How do I use geocoding to use an address instead? e.g. Cambridge, United Kingdom
Thanks
var map;
var geocoder;
var address;
function initialize() {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(40.730885,-73.997383), 15);
map.addControl(new GLargeMapControl);
GEvent.addListener(map, "click", getAddress);
geocoder = new GClientGeocoder();
}
function getAddress(overlay, latlng) {
if (latlng != null) {
address = latlng;
geocoder.getLocations(latlng, showAddress);
}
}
function showAddress(response) {
map.clearOverlays();
if (!response || response.Status.code != 200) {
alert("Status Code:" + response.Status.code);
} else {
place = response.Placemark[0];
point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(
'>b<orig latlng:>/b<' + response.name + '>br/<' +
'>b<latlng:>/b<' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '>br<' +
'>b<Status Code:>/b<' + response.Status.code + '>br<' +
'>b<Status Request:>/b<' + response.Status.request + '>br<' +
'>b<Address:>/b<' + place.address + '>br<' +
'>b<Accuracy:>/b<' + place.AddressDetails.Accuracy + '>br>' +
'>b>Country code:>/b< ' + place.AddressDetails.Country.CountryNameCode);
}
}

Resources