Add mouseover event to directionsRenderer Google Maps API v3 - javascript

How can I add a mouseover event listener to the directionsRenderer when using the DirectionsService?
I know how to add a listener to a straight line but can't seem to find the object in the directionsRenderer.
For example this works:
function getStraightLine(coordinates) {
if (progress.length == 0)
progress = coordinates;
else
progress.push(coordinates[1]);
updateDistance();
var line = new google.maps.Polyline({
path: coordinates,
strokeColor: "#FF0000",
strokeOpacity: .5,
strokeWeight: 2,
map: map
});
google.maps.event.addListener(line, 'mouseover', function(){
alert("moused over straight line!");
});
return line;
}
But this doesn't:
function getDirectionsPath(coordinates) {
var directionsPath = new google.maps.DirectionsRenderer();
directionsPath.setMap(map);
var request = {
origin: coordinates[0],
destination: coordinates[1],
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var coordinates = result.routes[0].overview_path;
if (progress.length == 0)
progress = coordinates;
else
progress = progress.concat(coordinates);
directionsPath.setDirections(result);
google.maps.event.addListener(directionsPath, 'mouseover', function(){
alert("moused over straight line!");
});
}
});
return directionsPath;
}
Instead of directionsPath I've tried result, result.routes[0], and a few others.
So what object should I use?

Will you use the 'drag' event on the 'polyline' that generated from the setDirections(directionsResult) method?
If you don't, I think you can create a 'polyline' by yourself like this:
directionsService.route(request, function (result, status)
{
var myRoute = result.routes[0].legs[0];
if (status == google.maps.DirectionsStatus.OK)
{
for (var i = 0; i < myRoute.steps.length; i++) {
for (var j = 0; j < myRoute.steps[i].lat_lngs.length; j++) {
points.push(myRoute.steps[i].lat_lngs[j]);
}
}
}
drawRoute();
}
function drawRoute()
{
var routLine = new google.maps.Polyline(
{
path: points,
strokeColor: "Red",
strokeOpacity: 0.5,
strokeWeight: 10
}
);
routLine.setMap(mapCanvas);
// Add a listener for the rightclick event on the routLine
*google.maps.event.addListener(routLine, 'mouseover', function(){
alert("moused over straight line!");
});*
}
if you have solved the problem use the method like google.maps.DirectionsRenderer().setDirections(result)?

The reason the second example doesn't work, is because there are no events associated with the object that the DirectionsRenderer() class produces. It produces a DirectionsResult object.
http://code.google.com/apis/maps/documentation/javascript/reference.html#DirectionsRenderer
Based on the docs:
http://code.google.com/apis/maps/documentation/javascript/reference.html#DirectionsResult
The DirectionsResult object contains an array of DirectionsRoutes. Using your code above, I would use the directionsPath object to get the routes: directionsPath.routes and then get the first route directionsPath.routes[0].
From there, you'll need to use the array of LatLngs in directionsPath.routes[0] to construct a polyline, with which then you can use the mouseover event.

Related

Cant get my marker's latLng to use in L.Routing.control

guys
I been trying to get my markers latlon when user double click on it but still don't get any results. Been trying other methods but i think this is the most accurate since i dont get any error when executing js
Any recommendation pls
var places = [
["LOCATION_1", 8.9856146341374, -79.51102268985925],
["LOCATION_2", 8.984640842221594, -79.51383510471848],
["LOCATION_3", 8.972080043026754, -79.5529245611453],
["LOCATION_4", 9.052896045979661, -79.4515923525883],
["LOCATION_5", 9.053366385577624, -79.50832832626823]
];
var map = L.map('map', {
center: [9.352867999999996, -79.689331],//[35.791188, -78.636755],
zoom: 9,
layers:L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
})
});
for (var i = 0; i < places.length; i++) {
marker = new L.marker([places[i][1], places[i][2]])
.bindPopup(places[i][0])
.addTo(map);
}
function getdest(){
L.marker.on('dblclick',function(e){
var latlng_dest=e.latlng() });
console.log(latlng_dest)
return latlng_dest
}
navigator.geolocation.getCurrentPosition(function(location) {
var latlng_orig = new L.LatLng(location.coords.latitude, location.coords.longitude);
L.Routing.control({
waypoints: [
//L.latLng(9.10607301250145, -79.34754531445351),
L.latLng(latlng_orig)
//,L.latLng(latlng_dest)
//,L.latLng(9.100769244670843, -79.35099352767948)
,L.latLng(getdest())
]
}).addTo(map)
});
You have many common things wrong:
e.latlng() is not a function it is a property e.latlng
L.marker.on('dblclick',function(e){ this makes no sense. You creating a new instance of a Marker without coords and then adding a listener to it.
You can't return a value in a function from a listener. The listener is not called at the moment you return the value L.marker.on('dblclick',function(e){ var latlng_dest=e.latlng() }); return latlng_dest
Your code should look like that:
for (var i = 0; i < places.length; i++) {
marker = new L.marker([places[i][1], places[i][2]])
.bindPopup(places[i][0])
.addTo(map)
.on('dblclick', function(e) {
waypoints.push(e.latlng);
routeControl.setWaypoints(waypoints);
});
}
var routeControl = L.Routing.control({
waypoints: [],
}).addTo(map);
var waypoints = [];
navigator.geolocation.getCurrentPosition(function(location) {
var latlng_orig = new L.LatLng(location.coords.latitude, location.coords.longitude);
waypoints.push(latlng_orig);
});

Google Map Direction Render Alternate Route How To Select Desired Path

I am working on google map directions I am following the google's navigation app.
I am able to get all the possible alternative routes by DirectionsService and can give the polylines different colors I want the user to be able to select his desired path just bu clicking on the poly lines some how have have not found any thing for this.
My code:
directionsService.route(request, function(response, status) {
var points = [];
if (status == google.maps.DirectionsStatus.OK) {
try {
var polycolour = "";
var Opacity = 0;
//var PolyLine = '';
for (var i = 0, len = response.routes.length; i < len; i++) {
if (i == 0) {
polycolour = "Blue";
Opacity = 5;
}
else {
polycolour = "grey";
Opacity = 2;
}
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
directions: response,
routeIndex: i,
draggable : true,
polylineOptions: {
strokeColor: polycolour,
strokeWeight: Opacity
}
});
var infowindow2 = new google.maps.InfoWindow();
//var step = 10;
//alert(angular.toJson(response.routes[0].legs[0].steps[i]));
infowindow2.setContent(""+((response.routes[i].legs[0].distance.value)/1000)+" KM");
infowindow2.setPosition(response.routes[i].legs[0].steps[8].end_location);
infowindow2.open(map);
}
//directionsDisplay.setMap(map);
google.maps.event.addListener(directionsDisplay, 'click', function(){
alert("helo");
});
//for (var k = 0, len = response.routes.length; k < len; k++) {
//var myRoute = response.routes[k].legs[0];
//for (var i = 0; i < myRoute.steps.length; i++) {
//for (var j = 0; j < myRoute.steps[i].lat_lngs.length; j++) {
// points.push(myRoute.steps[i].lat_lngs[j]);
//}
//}
//var routLine = new google.maps.Polyline(
//{
//path: points,
//strokeColor: "Red",
//strokeOpacity: 0.5,
// strokeWeight: 10
// }
// );
// }
// routLine.setMap(map)
// Add a listener for the rightclick event on the routLine
//google.maps.event.addListener(routLine, 'click', function(e){
//try {
//alert(angular.toJson(e));
//}
//catch (err)
//{
// alert(err);
//}
// });
//alert(angular.toJson(response.routes[0].legs[0].steps));
//google.maps.event.addListener(PolyLine, 'routeindex_changed', function() {
//alert("Bingo");
//computeTotalDistance(directionsDisplay.getRouteIndex());
//});
//alert(response.routes.length);
//directionsDisplay.setDirections(response);
}
catch (err)
{
alert(err);
}
}
});
First you need to tell the request that you want alternative routes, like this
// for example
var request = {
origin: start,
destination: end,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode[DRIVING]
};
Then you have multiple response.routes objects (notice, sometimes you only get 1 route).
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
for(var i in response.routes ) {
// ...
}
}
}
Now you can use response.routes[i] as the source for direction render.
Or you make your own polyline. Use response.routes[i].overview_path as the path
var line = new google.maps.Polyline({
path: response.routes[i].overview_path,
strokeColor: "#ff0000", // you might want different colors per suggestion
strokeOpacity: 0.7,
strokeWeight: 3
});
line.setMap(map);
Here is an functioning example.
Just change your API key.
As you asked for, clicking on a route highlights it
UPDATE: I like it this way.
Both grey lines and colored lines are generated. But highlighting only shows 1 of the suggestions on the map.
The big, grey line is nice to click on. So it gets the click event instead of the colored line.
This is also the easiest way to avoid the Z-index problem.
And I store data (duration, distance), that I show on an infoWindow
<!DOCTYPE html>
<html>
<head>
<title>Google Map Direction Render Alternate Route How To Select Desired Path</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 90%;
}
</style>
</head>
<body>
<form id="form">
<input id="from" placeholder="From" value="Brussel" />
<input id="to" placeholder="To" value="Antwerpen" />
<input type="submit" value="GO" />
</form>
<div id="map"></div>
<div id="info">
Stackoverflow
</div>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry"></script>
<script>
var map;
var directionsService;
var polylines = [];
var shadows = [];
var data = [];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.84659376378408, lng: 4.3531406857355215},
zoom: 12,
mapTypeId: 'terrain'
});
google.maps.event.addDomListener(document.getElementById('form'), 'submit', function(e) {
calcRoute(
document.getElementById('from').value,
document.getElementById('to').value
);
// prevent the form from really submitting
e.preventDefault();
return false;
});
directionsService = new google.maps.DirectionsService();
// get the bounds of the polyline
// http://stackoverflow.com/questions/3284808/getting-the-bounds-of-a-polyine-in-google-maps-api-v3
google.maps.Polyline.prototype.getBounds = function(startBounds) {
if(startBounds) {
var bounds = startBounds;
}
else {
var bounds = new google.maps.LatLngBounds();
}
this.getPath().forEach(function(item, index) {
bounds.extend(new google.maps.LatLng(item.lat(), item.lng()));
});
return bounds;
};
}
// this function calculates multiple suggested routes.
// We will draw 3 (broad stroke) suggested routs in grey. These are broad to click on them easier.
// We duplicate these routes with a thin, colored line; only route 0 is shown.
function calcRoute(start, end) {
var request = {
origin: start,
destination: end,
provideRouteAlternatives: true,
unitSystem: google.maps.UnitSystem.METRIC,
travelMode: google.maps.TravelMode['DRIVING']
};
directionsService.route(request, function(response, status) {
// clear former polylines
for(var j in polylines ) {
polylines[j].setMap(null);
shadows[j].setMap(null);
}
polylines = [];
shadows = [];
data = [];
if (status == google.maps.DirectionsStatus.OK) {
var bounds = new google.maps.LatLngBounds();
for(var i in response.routes) {
// let's make the first suggestion highlighted;
var hide = (i==0 ? false : true);
var shadow = drawPolylineShadow(response.routes[i].overview_path, '#666666');
var line = drawPolyline(response.routes[i].overview_path, '#0000ff', hide);
polylines.push(line);
shadows.push(shadow);
// let's add some data for the infoWindow
data.push({
distance: response.routes[i].legs[0].distance,
duration: response.routes[i].legs[0].duration,
end_address: response.routes[i].legs[0].end_address,
start_address: response.routes[i].legs[0].start_address,
end_location: response.routes[i].legs[0].end_location,
start_location: response.routes[i].legs[0].start_location
});
bounds = line.getBounds(bounds);
google.maps.event.addListener(shadow, 'click', function(e) {
// detect which route was clicked on
var index = shadows.indexOf(this);
highlightRoute(index, e);
});
}
map.fitBounds(bounds);
}
});
}
// this makes one of the colored routes visible.
function highlightRoute(index, e) {
for(var j in polylines ) {
if(j==index) {
//var color = '#0000ff';
polylines[j].setMap(map);
// feel free to customise this string
var contentString =
'<span>'+ data[j].distance.text +'</span><br/>'+
'<span>'+ data[j].duration.text +'</span><br/>'+
'<span>route: '+ j +'</span><br/>'+
//'From: <span>'+ data[j].start_address +'</span><br/>'+
//'To: <span>'+ data[j].end_address +'</span><br/>'+
'';
if(e) {
var position = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
// it may be needed to close the previous infoWindow
if(infowindow) {
infowindow.close();
infowindow = null;
}
infowindow = new google.maps.InfoWindow({
content: contentString,
position: position,
map: map
});
//infowindow.open(map, polylines[j]);
}
}
else {
polylines[j].setMap(null);
}
}
}
// returns a polyline.
// if hide is set to true, the line is not put on the map
function drawPolyline(path, color, hide) {
var line = new google.maps.Polyline({
path: path,
strokeColor: color,
strokeOpacity: 0.9,
strokeWeight: 3
});
if(! hide) {
line.setMap(map);
}
return line;
}
function drawPolylineShadow(path, color, hide) {
var line = new google.maps.Polyline({
path: path,
strokeColor: color,
strokeOpacity: 0.4,
strokeWeight: 7
});
if(! hide) {
line.setMap(map);
}
return line;
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>
</body>
</html>
earlier code. this changes the color of the polyLine
<!DOCTYPE html>
<html>
<head>
<title>Suggested routes</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 90%;
}
</style>
</head>
<body>
<form id="form">
<input id="from" placeholder="From" value="Brussel" />
<input id="to" placeholder="To" value="Antwerpen" />
<input type="submit" value="GO" />
</form>
<div id="map"></div>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry"></script>
<script>
var map;
var directionsService;
var polylines = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.84659376378408, lng: 4.3531406857355215},
zoom: 12,
mapTypeId: 'terrain'
});
google.maps.event.addDomListener(document.getElementById('form'), 'submit', function(e) {
calcRoute(
document.getElementById('from').value,
document.getElementById('to').value
);
// prevent the form from really submitting
e.preventDefault();
return false;
});
directionsService = new google.maps.DirectionsService();
// get the bounds of the polyline
// http://stackoverflow.com/questions/3284808/getting-the-bounds-of-a-polyine-in-google-maps-api-v3
google.maps.Polyline.prototype.getBounds = function(startBounds) {
if(startBounds) {
var bounds = startBounds;
}
else {
var bounds = new google.maps.LatLngBounds();
}
this.getPath().forEach(function(item, index) {
bounds.extend(new google.maps.LatLng(item.lat(), item.lng()));
});
return bounds;
};
}
function calcRoute(start, end) {
var request = {
origin: start,
destination: end,
provideRouteAlternatives: true,
unitSystem: google.maps.UnitSystem.METRIC,
travelMode: google.maps.TravelMode['DRIVING']
};
directionsService.route(request, function(response, status) {
// clear former polylines
for(var j in polylines ) {
polylines[j].setMap(null);
}
polylines = [];
if (status == google.maps.DirectionsStatus.OK) {
var bounds = new google.maps.LatLngBounds();
// draw the lines in reverse orde, so the first one is on top (z-index)
for(var i=response.routes.length - 1; i>=0; i-- ) {
// let's make the first suggestion highlighted;
if(i==0) {
var color = '#0000ff';
}
else {
var color = '#999999';
}
var line = drawPolyline(response.routes[i].overview_path, color);
polylines.push(line);
bounds = line.getBounds(bounds);
google.maps.event.addListener(line, 'click', function() {
// detect which route was clicked on
var index = polylines.indexOf(this);
highlightRoute(index);
});
}
map.fitBounds(bounds);
}
});
}
function highlightRoute(index) {
for(var j in polylines ) {
if(j==index) {
var color = '#0000ff';
}
else {
var color = '#999999';
}
polylines[j].setOptions({strokeColor: color});
}
}
function drawPolyline(path, color) {
var line = new google.maps.Polyline({
path: path,
strokeColor: color,
strokeOpacity: 0.7,
strokeWeight: 3
});
line.setMap(map);
return line;
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>
</body>
</html>

Create elevation profile from GeoJson feature

I have a map which contains a GeoJson file with lines, displaying some trails. Is it possible to use Google Maps API Elevation Service to create elevation profiles for every feature line of the GeoJson file? I want the elevation profile to be displayed when I click one of the lines.
Something like this example: http://www.trailforks.com/region/la-bouilladisse/
My code, until now, looks like this:
google.load("visualization", "1", {packages: ["columnchart"]});
function initialize() {
var options = {
center: new google.maps.LatLng(44.701991, 22.624884),
zoom: 12,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), options);
trasee = new google.maps.Data()
trasee.loadGeoJson('http://googledrive.com/host/0B55_4P6vMjhITEU4Ym9iVG8yZUU/trasee.geojson')
trasee.setMap(map)
styling = (function(feature) {
var clasificare = feature.getProperty('Tip_drum');
var culoare;
if (clasificare == ('Poteca'))
(culoare = 'brown')
else if (clasificare == ('Drum forestier'))
(culoare = 'green')
else if (clasificare == ('Drum comunal (neasfaltat)'))
(culoare = 'brown')
else if (clasificare == ('Drum judetean (neasfaltat)'))
(culoare = 'brown')
else if (clasificare == ('Drum comunal (asfaltat)'))
(culoare = 'gray')
else if (clasificare == ('Drum judetean (asfaltat)'))
(culoare = 'gray')
else
(culoare = 'black')
return ({
strokeColor: culoare,
strokeWeight: 3
})
})
trasee.setStyle(styling)
elevator = new google.maps.ElevationService();
}
I know that I have to make a request like this:
var pathRequest = {
'path': source of latlng for creating the path
'samples': 256
}
So basically, I think that the GeoJson must be added somewhere in the pathRequest, but I don't know how, and how to create a different elevation plot for every feature in my GeoJson file.
fiddle of existing code
OK, so now I try to display the elevation charts along with the Tip_drum attribute in infowindows, when I click the data. I added this code:
map.data.addListener('click', function (event) {
document.getElementById('info').innerHTML = event.feature.getProperty('Tip_drum')
var content = document.createElement('div')
var elevations = document.getElementById('elevation_chart')
var types = document.getElementById('info')
content.appendChild(elevations)
content.appendChild(types)
infowindow.setContent(content)
infowindow.setPosition(event.latLng)
infowindow.setMap(map)
if (event.feature.getGeometry().getType() === 'LineString') {
drawPath(event.feature.getGeometry().getArray());
Everything works fine, until I manually close one of the infowindows. After that, the infowindows won't appear anymore.
get the path from the clicked feature (event.feature.getGeometry().getArray())
pass it to the elevation service (like the example in the elevations service documentation)
plot the returned data on a chart (like the example in the elevations service documentation)
remove the code from the Google elevation service example that creates a blue polyline over the polylines from the data layer.
(note that some of the above didn't work with your existing code, I modified it slightly to match the working examples in the documentation)
working fiddle
var elevator;
var map;
var chart;
var polyline;
// Load the Visualization API and the columnchart package.
google.load('visualization', '1', {
packages: ['columnchart']
});
function initialize() {
var options = {
center: new google.maps.LatLng(44.701991, 22.624884),
zoom: 12,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), options);
trasee = new google.maps.Data();
map.data.loadGeoJson('http://googledrive.com/host/0B55_4P6vMjhITEU4Ym9iVG8yZUU/trasee.geojson');
// trasee.setMap(map);
styling = (function (feature) {
var clasificare = feature.getProperty('Tip_drum');
var culoare;
if (clasificare == ('Poteca'))
(culoare = 'brown');
else if (clasificare == ('Drum forestier'))
(culoare = 'green');
else if (clasificare == ('Drum comunal (neasfaltat)'))
(culoare = 'brown');
else if (clasificare == ('Drum judetean (neasfaltat)'))
(culoare = 'brown');
else if (clasificare == ('Drum comunal (asfaltat)'))
(culoare = 'gray');
else if (clasificare == ('Drum judetean (asfaltat)'))
(culoare = 'gray');
else(culoare = 'black');
return ({
strokeColor: culoare,
strokeWeight: 3
});
});
map.data.setStyle(styling);
// Set mouseover event for each feature.
map.data.addListener('click', function (event) {
document.getElementById('info').innerHTML = event.feature.getProperty('Tip_drum');
if (event.feature.getGeometry().getType() === 'LineString') {
drawPath(event.feature.getGeometry().getArray());
// calculate the directions once both origin and destination are set
// calculate();
}
});
// When the user hovers, tempt them to click by outlining the letters.
// Call revertStyle() to remove all overrides. This will use the style rules
// defined in the function passed to setStyle()
map.data.addListener('mouseover', function(event) {
map.data.revertStyle();
map.data.overrideStyle(event.feature, {strokeWeight: 8, strokeColor: 'blue'});
});
map.data.addListener('mouseout', function(event) {
map.data.revertStyle();
});
elevator = new google.maps.ElevationService();
// Draw the path, using the Visualization API and the Elevation service.
// drawPath();
}
function drawPath(path) {
// Create a new chart in the elevation_chart DIV.
chart = new google.visualization.ColumnChart(document.getElementById('elevation_chart'));
// Create a PathElevationRequest object using this array.
// Ask for 256 samples along that path.
var pathRequest = {
'path': path,
'samples': 256
};
// Initiate the path request.
elevator.getElevationAlongPath(pathRequest, plotElevation);
}
// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation(results, status) {
if (status != google.maps.ElevationStatus.OK) {
return;
}
var elevations = results;
// Extract the elevation samples from the returned results
// and store them in an array of LatLngs.
var elevationPath = [];
for (var i = 0; i < results.length; i++) {
elevationPath.push(elevations[i].location);
}
// Extract the data from which to populate the chart.
// Because the samples are equidistant, the 'Sample'
// column here does double duty as distance along the
// X axis.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation');
for (var i = 0; i < results.length; i++) {
data.addRow(['', elevations[i].elevation]);
}
// Draw the chart using the data within its DIV.
document.getElementById('elevation_chart').style.display = 'block';
chart.draw(data, {
height: 150,
legend: 'none',
titleY: 'Elevation (m)'
});
}
google.maps.event.addDomListener(window, 'load', initialize);

How To Add Event In Array Of Google Maps Polygon. Only Some of Them Have the Event

All. I'm developing dashboard application which uses google maps API. I'm trying to render many google.maps.Polygon in a map.
Once it loads polygon data from AJAX request, I created some polygons, and I store them in array. For each loop of creating polygon,
I added google maps event to every polygon (mouseover, mouseout, and click event). It succesfully rendered all polygon on the map. But
not all polygon has event, just some of them. Would you like to give me some solutions of this problem?
Here is the part of code
function big_loadMapCells() {
var serviceUrl = './Services/example';
var currentIdx = 0;
var pagingCount = 5000;
while (currentIdx < totalCount) {
// send ajax
Ext.Ajax.request({
method: "GET",
url: serviceUrl + '?start=' + currentIdx + '&limit=' + pagingCount,
timeout: 300000,
success: function (c) {
var jsonObj = Ext.JSON.decode(c.responseText);
if (jsonObj) {
big_createCellsFromJSON(jsonObj);
}
}
});
currentIdx += pagingCount;
}
}
function big_createCellsFromJSON(jsonObj) {
// looping for creating polygon
for (var a = 0; a < jsonObj.items.length; a++) {
var cellJson = jsonObj.items[a];
var data = {
lacCi: cellJson.LACCI
tech: cellJson.TECH,
periodType: cellJson.PERIOD_TIME,
time: cellJson.DATETIME_ID,
region: cellJson.REGION,
latitude: cellJson.LATITUDE,
longitude: cellJson.LONGITUDE,
node: cellJson.NODE,
siteName: cellJson.SITE,
kpi: cellJson.KPI,
cellName: cellJson.CELL_NAME,
azimuth: cellJson.AZIMUTH,
beamWidth: width,
beamConst: radius,
color: cellJson.COLOR
};
var myCell = big_createCellPolygon(data);
big_arrCells.push(myCell);
}
}
function big_createCellPolygon(data) {
// create polygon using my own javascript, CELL object
var myCell = new CELL();
myCell.setOptions({
paths: myCell.pts,
strokeColor: myCell.color,
strokeOpacity: 0.8,
strokeWeight: 0,
fillColor: myCell.color,
fillOpacity: 0.5,
map: big_map
});
function addCellEvent(myCell) {
google.maps.event.addListener(myCell, 'mouseover', function () {
this.setOptions({
strokeWeight: 1,
fillOpacity: 0.7
});
});
google.maps.event.addListener(myCell, 'mouseout', function () {
this.setOptions({
strokeWeight: 0,
fillOpacity: 0.5
});
});
google.maps.event.addListener(myCell, 'click', function (evt) {
big_createInfoWindowCell(data, evt.latLng);
});
}
addCellEvent(myCell);
return myCell;
}
big_loadMapCells();

google maps v3: Invalid value for constructor parameter 0 while drawing polylines

I have a problem when constructing a polygon. The error message says something like:
Invalid value for constructor parameter 0: (49.27862248020283, -122.79301448410035),(49.277964542440955, -122.79370112960816),(49.278524490028595, -122.7950207764435)
It must be something ridiculously simple, but I just can't see it. Any tips you have are useful.
I'm basically painting a map inside an iframe on a modal window (with wicket). Everything is ok, but when I'm trying show a polygon (the points are loaded from a database and sent by webservice) I get the error message.
iframe code: (only the relevant)
/**
* Draws the polygon.
*/
function drawPolygon() {
if (order >= 3) {
deleteMarkers();
// Construct the polygon
// Note that we don't specify an array or arrays, but instead just
// a simple array of LatLngs in the paths property
polygonObject = new google.maps.Polygon({
paths: polygonCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
});
polygonObject.setMap(map);
isPolygonDrawed = true;
//After we create the polygon send the points to wicket
parent.sendPoints();
//Change the message on the top label
controlText.style.color = '#ADAAAA';
controlText.innerHTML = polygonCreated;
//With this we make sure no other markers are created after the polygon is drawed.
//Is assigned (order - 1) because when this code is called the order has already been added 1.
MAX_POLYGON_VERTEX = order - 1;
//Disable the create polygon button.
enable = false;
createControlText.style.color = '#ADAAAA';
}
else alert(alertMessage);
}
Now the code on the parent (the modal window)
/**
* Show the polygon on map.
*/
function showPolygon(zoneId) {
var url = applicationRootUrl + 'zonePointsOnMap?zoneId=' + zoneId;
$.getJSON(url, function(data) {
if(data.length == 0) {
return false;
}
frames['zoneMapIFrame'].order = parseInt(data.length);
alert(data.length);
$.each(data, function(i, item) {
if(item != null) {
if(item.latitude != null && item.longitude != null) {
var lat = parseFloat(item.latitude);
var lng = parseFloat(item.longitude);
var latlng = new google.maps.LatLng(lat, lng);
var pointOrder = item.order;
frames['zoneMapIFrame'].polygonCoords[pointOrder] = latlng;
alert(item.order + " point " + latlng);
frames['zoneMapIFrame'].bounds.extend(latlng);
}
}
});
});
setTimeout("frames['zoneMapIFrame'].drawPolygon()", 200);
setTimeout("frames['zoneMapIFrame'].fitMapZoomPolygon()", 300);
}
I can see that the points are loaded ok with alerts, but I keep getting the error message.
Help me!
I was having the same problem.
Don't know if its the best solution, probably not, but it worked for me.
The problem was that the Latlng weren't being recognized. So I recreated the array.
var lats = [];
var lat_size = steps[step].lat_lngs.length;
for (var t=0; t <lat_size; t++) {
lats.push(new google.maps.LatLng(steps[step].lat_lngs[t].lat(), steps[step].lat_lngs[t].lng()))
}
var polylineOptions = {
map: map,
path: lats
}
new google.maps.Polyline(polylineOptions);

Categories

Resources