Adding Play/Pause to WebGL, in PHP JS only - javascript

I am trying to add a Play/Pause button to the Advanced API controls, I have the button.value changing from the ascii #9654 to #9646 but the rest of the code to start the animation and stop it is not working? The sphere will rotate if the 'requestanimationframe' is contained within the 'init()' of the WebGl it's self. You can see the working sphere at No controls and the one I'm adding controls in Placing controls but animation play/pause not working, thanks for any ideas.
I left in //hard coded markers if you need to run it yourself just comment out the php section of DB access.
<!DOCTYPE HTML>
<html>
<head>
<script src="http://www.webglearth.com/v2/api.js"></script>
<script>
function initialize() {
var options = {
sky: true,
atmosphere: true,
dragging: true,
tilting: false
};//options
var earth = new WE.map('earth_div');
earth.setView([30.0, -87.65], 3);
WE.tileLayer('http://data.webglearth.com/natural-earth-color/{z}/{x}/{y}.jpg', {
tileSize: 256,
bounds: [[-85, -180], [85, 180]],
minZoom: 2,
maxZoom: 9,
tms: true
}).addTo(earth);//tilelayer
var toner = WE.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
opacity: 0.25
});//toner
toner.addTo(earth);
earth.setZoom(3);
document.getElementById('zoom_level').addEventListener('change', function(e) {
earth.setZoom(e.target.value);
});//setZoom
// earth.setTilt(40);
// document.getElementById('tilt_level').addEventListener('change', function(e) {
// earth.setTilt(e.target.value);
// });//setTilt-not working look at .setview
/* // Add markers - Hard coded works.
var marker = WE.marker([48.45, 34.9833], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker.bindPopup("86.110.118.194", {maxWidth: 90, closeButton: true}).openPopup();
var marker2 = WE.marker([41.85, -87.65], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker2.bindPopup("174.221.5.127", {maxWidth: 90, closeButton: true}).openPopup();
var marker3 = WE.marker([44.3051,-69.977], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker3.bindPopup("142.105.199.149", {maxWidth: 90, closeButton: true}).openPopup();
*/
//Get GPS lat/lon from sql Db for markers
<?php
include('ts.php');
// Add markers
$ct = 0;
$i = 1;
$lat1 = ""; $lat2 = "";
$lon1 = ""; $lon2 = "";
$row = array();
$rows = array($row);
$con = mysql_connect("localhost","User","Password");
$db_selected = mysql_select_db("DB", $con);
if (!$db_selected){echo mysql_errno($con) . ": " . mysql_error($con) . "\n";}
$query = "SELECT `gpslat`, `gpslon`, `ip` FROM `visitor_tracker` ORDER BY `gpslat` DESC";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$lat1 = $row[0];
//$lon1 = $row[1];
if ($ct == 0) {$rows[] = $row;
$lat2 = $rows[$i][0];
//$lon2 = $rows[$i][1];
}//if
Else {if ($lat1 != $lat2){
$rows[] = $row;
$i = $i+1;
$lat2 = $rows[$i][0];
//$lon2 = $rows[$i-1][1];
}//if
}//else
$ct = $ct+1;
}//while
mysql_free_result($result);
mysql_close($con);
?>
// Populate markers
var markers = <?php echo json_encode($rows); ?>;
var ygpslat = <?php echo json_encode($gpslat); ?>;
var ygpslon = <?php echo json_encode($gpslon); ?>;
var yip = <?php echo json_encode($ip); ?>;
for(var i = 1, len = markers.length; i < len; i++) {
var marker = WE.marker([markers[i][0],markers[i][1]], 'http://eagleeye360.com/worldmap/pin_green.jpg', 4, 4).addTo(earth);
marker.bindPopup(markers[i][2], {maxWidth: 100, closeButton: true}).closePopup();
}//for
//Your marker
var marker = WE.marker([ygpslat,ygpslon], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker.bindPopup("<center>You</br>"+yip, {maxWidth: 100, closeButton: true}).openPopup();
}//init()
function rotate_play_pause() {
var status = document.getElementById("rotate_button");
if (status.value == String.fromCharCode(9654)) {
document.getElementById("rotate_button").value = String.fromCharCode(9646);
// Start a simple rotation animation
var before = null;
requestAnimationFrame(function animate(now) {
var c = earth.getPosition();
var elapsed = before? now - before: 0;
before = now;
earth.setCenter([c[0], c[1] - 0.1*(elapsed/30)]);
requestAnimationFrame(animate);
});//requestAnimationFrame
} else {
document.getElementById("rotate_button").value = String.fromCharCode(9654);
cancelAnimationFrame(animate);
}//if else
}//function rotate_play_pause()
// document.getElementById('cesium-credit-text').innerHTML = "EagleEye360.com-Visitors/Bots/HackAttempts";
</script>
<style type="text/css">
html, body{padding: 0; margin: 0; background-color: black;}
#earth_div{top: 0; right: 0; bottom: 0; left: 0; position: absolute !important;}
#coords{position: absolute; bottom: 10px; right: 10px; z-index: 100000;}
#buttons {position: absolute; bottom:10px; left: 10px; color: #808080;}
</style>
<title>EagleEye360 Test 1</title>
</head>
<body onload="initialize()">
<div id="earth_div"></div>
<div id="buttons">
<center><input type="button" id="rotate_button" value="&#9654" class="play" onclick="rotate_play_pause();"><center/><br>
<center>Zoom</center>
2<input type="range" id="zoom_level" min="2" max="9" step="1.0" value="3.0">9<br>
<center>Tilt</center>
40&#176<input type="range" id="tilt_level" min="40" max="130" step="5" value="40">130&#176<br>
</div>
</body>
</html>

After 10 days of trying, I have solved the issue with this code :)
The problem was that Java Script does not pass vars as other languages it passes a dynamic of the var so anything done to a var with in a function will leave the original var unchanged - unless it is a Global var.
I added Global vars: Earth and myReq(for canx the request) the entire code is:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="CSS/vertical-text.css" type="text/css"/>
<script src="http://www.webglearth.com/v2/api.js"></script>
<script>
var earth = undefined;
var myReq;
function initialize() {
var options = {
sky: true,
atmosphere: true,
dragging: true,
tilting: false,
scrollWheelZoom: false
};//options
earth = new WE.map('earth_div');
earth.setView([30.0, -87.65], 3);
WE.tileLayer('http://data.webglearth.com/natural-earth-color/{z}/{x}/{y}.jpg', {
tileSize: 256,
bounds: [[-85, -180], [85, 180]],
minZoom: 2,
maxZoom: 9,
tms: true,
attribution: '© EagleEye360.com'
}).addTo(earth);//tilelayer
var toner = WE.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
opacity: 0.15 // or use http://{s}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png
});//toner
toner.addTo(earth);
document.getElementById('opacity2').addEventListener('change', function(e) {
toner.setOpacity(e.target.value);
});//set opacity
earth.setZoom(3);
document.getElementById('zoom_level').addEventListener('change', function(e) {
earth.setZoom(e.target.value);
});//setZoom
//rotate_play_pause();
document.getElementById('rotate_button').addEventListener('change', function(e) {
rotate_play_pause();
});//rotate_play_pause()
// earth.setTilt(40);
// document.getElementById('tilt_level').addEventListener('change', function(e) {
// earth.setTilt(e.target.value);
// });//setTilt-not working look at .setview
/* // Add markers - Hard coded works.
var marker = WE.marker([48.45, 34.9833], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker.bindPopup("86.110.118.194", {maxWidth: 90, closeButton: true}).openPopup();
var marker2 = WE.marker([41.85, -87.65], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker2.bindPopup("174.221.5.127", {maxWidth: 90, closeButton: true}).openPopup();
var marker3 = WE.marker([44.3051,-69.977], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker3.bindPopup("142.105.199.149", {maxWidth: 90, closeButton: true}).openPopup();
*/
<?php
include('ts.php');
// Add markers
$ct = 0;
$i = 1;
$lat1 = ""; $lat2 = "";
$lon1 = ""; $lon2 = "";
$row = array();
$rows = array($row);
$con = mysql_connect("localhost","hogansba_Jon","Tigger09<>");
$db_selected = mysql_select_db("hogansba_EagleEye", $con);
if (!$db_selected){echo mysql_errno($con) . ": " . mysql_error($con) . "\n";}
$query = "SELECT `gpslat`, `gpslon`, `ip` FROM `visitor_tracker` ORDER BY `gpslat` DESC";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$lat1 = $row[0];
//$lon1 = $row[1];
if ($ct == 0) {$rows[] = $row;
$lat2 = $rows[$i][0];
//$lon2 = $rows[$i][1];
}//if
Else {if ($lat1 != $lat2){
$rows[] = $row;
$i = $i+1;
$lat2 = $rows[$i][0];
//$lon2 = $rows[$i-1][1];
}//if
}//else
$ct = $ct+1;
}//while
mysql_free_result($result);
mysql_close($con);
?>
// Populate markers
var markers = <?php echo json_encode($rows); ?>;
var ygpslat = <?php echo json_encode($gpslat); ?>;
var ygpslon = <?php echo json_encode($gpslon); ?>;
var yip = <?php echo json_encode($ip); ?>;
for(var i = 1, len = markers.length; i < len; i++) {
var marker = WE.marker([markers[i][0],markers[i][1]], 'http://eagleeye360.com/worldmap/pin_green.jpg', 4, 4).addTo(earth);
marker.bindPopup(markers[i][2], {maxWidth: 100, closeButton: true}).closePopup();
}//for
//Your marker
var marker = WE.marker([ygpslat,ygpslon], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
marker.bindPopup("<div class='container'><div class='rotated-text'><span class='rotated-text__inner'><center><?php echo 'You-',$ip?><center/></span></div></div>", {maxWidth: 14, closeButton: true}).openPopup();
earth.setView([ygpslat,ygpslon], 3);
}//init()
function rotate_play_pause() {
var before = null;
var status = document.getElementById("rotate_button");
if (status.value == String.fromCharCode(9654)) {
document.getElementById("rotate_button").value = String.fromCharCode(9646);
// Start a simple rotation animation
requestAnimationFrame(function animate(now) {
var c = earth.getPosition();
var elapsed = before? now - before: 0;
before = now;
earth.setCenter([c[0], c[1] - 0.1*(elapsed/30)]);
myReq = requestAnimationFrame(animate);
});//requestAnimationFrame
} else {
cancelAnimationFrame(myReq);
document.getElementById("rotate_button").value = String.fromCharCode(9654);
}//if else
}//function rotate_play_pause()
// document.getElementById('cesium-credit-text').innerHTML = "EagleEye360.com-Visitors/Bots/HackAttempts";
</script>
<style type="text/css">
html, body{padding: 0; margin: 0; background-color: black;}
#earth_div{top: 0; right: 0; bottom: 0; left: 0; position: absolute !important;}
#coords{position: absolute; bottom: 10px; right: 10px; z-index: 100000;}
#buttons {position: absolute; bottom:10px; left: 10px; color: #808080;}
</style>
<title>EagleEye360 Test 1</title>
</head>
<body onload="initialize()">
<div id="earth_div"></div>
<div id="buttons">
<center><input type="button" id="rotate_button" value="&#9654" class="play" onclick="rotate_play_pause();"><center/><br>
<center>Zoom</center>
2<input type="range" id="zoom_level" min="2" max="9" step="1.0" value="3.0">9<br>
<center>Streetmap opacity</center>
0<input type="range" id="opacity2" min="0" max="1" step="0.05" value="0.15">1<br>
<center><p>Total Hits: <?php echo $ct ?></br>Unique Visitors: <?php echo $i ?><p/></center>
</div>
</body>
</html>
You can see it working Here I will leave it up for about a month after that it will no longer be available.
Jon

Related

I want to create Stacked Chart from JSON in google chart

help, I want to create stacked chart from JSON in google chart, honestly my problem is var data = google.visualization.arrayToDataTable([ this is my codes
<?php
$tmp = array();
require "configdashboard.php";
/*
select the 3 columns of interest, assinging aliases for laziness purposes
*/
$sql = "SELECT devices.device_id AS device_id, devices.hostname AS hostname, devices.ip, devices.uptime, SUM(storage.storage_used) AS storage_used, SUM(storage.storage_free) AS storage_free , storage.storage_descr AS storage_descr
FROM storage
INNER JOIN devices ON storage.device_id = devices.device_id GROUP BY devices.device_id, storage.storage_descr";
$conn = mysqli_connect('localhost', 'root', '', 'monitoring');
$query = mysqli_query($conn, $sql);
$fetch = mysqli_fetch_assoc($query);
if ($stmt = $connection->query($sql)) {
while ($row = $stmt->fetch_assoc()) {
/* Add each row with named columns - which makes working with the JSON in Javascript easier IMO */
$tmp[] = array(
'device_id' => $row['device_id'],
'storage_used' => $row['storage_used'],
'storage_free' => $row['storage_free'],
'hostname' => $row['hostname'],
'storage_descr' => $row['storage_descr']
);
}
}
# create the JSON string
$json = json_encode($tmp);
//$json=json_encode( $fetch );
//print_r ($json);
?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
var my_2d = <?php echo $json; ?>;
google.charts.load('current', {
packages: ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
if (Object.keys(my_2d).length > 0) {
for (i = 0; i < my_2d.length; i++) {
var data = google.visualization.arrayToDataTable([
['Task', 'Server Devices ' + my_2d[i].device_id + ' ' + my_2d[i].hostname],
['Used', parseInt(my_2d[i].storage_used)],
['Free', parseInt(my_2d[i].storage_free)]
]);
var options_fullStacked = {
isStacked: 'percent',
height: 300,
legend: {
position: 'top',
maxLines: 2
},
hAxis: {
minValue: 0,
ticks: [0, .3, .6, .9, 1]
}
};
var table = document.getElementById("table_chart");
if (i % 2 == 0) {
var tr = document.createElement("tr");
tr.setAttribute("class", "row_chart")
table.appendChild(tr)
}
var row_charts = document.getElementsByClassName("row_chart")
var td = document.createElement("td");
var div = document.createElement("div")
div.setAttribute("id", 'chart_div_' + i)
div.setAttribute("style", 'width: auto; height: auto; display: block; margin: auto;')
var lastTr = row_charts.length - 1
row_charts[lastTr].appendChild(td)
td.appendChild(div)
var chart = new google.visualization.BarChart(div);
chart.draw(data, options_fullStacked);
}
}
}
</script>
this is my database
and i want to create like this *note /, /run etc is storage_descr
but my output now
Looks like you have two separate series, Used and Free. You want one series as a stacked bar.
Try follwing the was they sample the table and chart setup here:
https://developers.google.com/chart/interactive/docs/gallery/barchart
var options = {
width: 600,
height: 400,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '75%' },
isStacked: true
};

no api-key error massage

I have tried many ways and many places to enter the API key for but in all the cases, I get the error no-API-key. the request works fine in the postman, meaning the key works fine.
the places I tried:
where I mentioned in this code
at the end of snap to road request call
at the end of all the request calls
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Roads API Demo</title>
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#bar {
width: 240px;
background-color: rgba(255, 255, 255, 0.75);
margin: 8px;
padding: 4px;
border-radius: 4px;
}
#autoc {
width: 100%;
box-sizing: border-box;
}
</style>
<script src="/_static/js/jquery-bundle.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places"></script>
<script>
var apiKey = 'I PUTTED THE KEY HERE IN THE LAST TRY';
var map;
var drawingManager;
var placeIdArray = [];
var polylines = [];
var snappedCoordinates = [];
function initialize() {
var mapOptions = {
zoom: 17,
center: {lat: -33.8667, lng: 151.1955}
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Adds a Places search box. Searching for a place will center the map on that
// location.
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(
document.getElementById('bar'));
var autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autoc'));
autocomplete.bindTo('bounds', map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
});
// Enables the polyline drawing control. Click on the map to start drawing a
// polyline. Each click will add a new vertice. Double-click to stop drawing.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYLINE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYLINE
]
},
polylineOptions: {
strokeColor: '#696969',
strokeWeight: 2
}
});
drawingManager.setMap(map);
// Snap-to-road when the polyline is completed.
drawingManager.addListener('polylinecomplete', function(poly) {
var path = poly.getPath();
polylines.push(poly);
placeIdArray = [];
runSnapToRoad(path);
});
// Clear button. Click to remove all polylines.
$('#clear').click(function(ev) {
for (var i = 0; i < polylines.length; ++i) {
polylines[i].setMap(null);
}
polylines = [];
ev.preventDefault();
return false;
});
}
// Snap a user-created polyline to roads and draw the snapped path
function runSnapToRoad(path) {
var pathValues = [];
for (var i = 0; i < path.getLength(); i++) {
pathValues.push(path.getAt(i).toUrlValue());
}
$.get('https://roads.googleapis.com/v1/snapToRoads', {
interpolate: true,
key: apiKey,
path: pathValues.join('|')
}, function(data) {
processSnapToRoadResponse(data);
drawSnappedPolyline();
getAndDrawSpeedLimits();
});
}
// Store snapped polyline returned by the snap-to-road service.
function processSnapToRoadResponse(data) {
snappedCoordinates = [];
placeIdArray = [];
for (var i = 0; i < data.snappedPoints.length; i++) {
var latlng = new google.maps.LatLng(
data.snappedPoints[i].location.latitude,
data.snappedPoints[i].location.longitude);
snappedCoordinates.push(latlng);
placeIdArray.push(data.snappedPoints[i].placeId);
}
}
// Draws the snapped polyline (after processing snap-to-road response).
function drawSnappedPolyline() {
var snappedPolyline = new google.maps.Polyline({
path: snappedCoordinates,
strokeColor: 'black',
strokeWeight: 3
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
}
// Gets speed limits (for 100 segments at a time) and draws a polyline
// color-coded by speed limit. Must be called after processing snap-to-road
// response.
function getAndDrawSpeedLimits() {
for (var i = 0; i <= placeIdArray.length / 100; i++) {
// Ensure that no query exceeds the max 100 placeID limit.
var start = i * 100;
var end = Math.min((i + 1) * 100 - 1, placeIdArray.length);
drawSpeedLimits(start, end);
}
}
// Gets speed limits for a 100-segment path and draws a polyline color-coded by
// speed limit. Must be called after processing snap-to-road response.
function drawSpeedLimits(start, end) {
var placeIdQuery = '';
for (var i = start; i < end; i++) {
placeIdQuery += '&placeId=' + placeIdArray[i];
}
$.get('https://roads.googleapis.com/v1/speedLimits',
'key=' + apiKey + placeIdQuery,
function(speedData) {
processSpeedLimitResponse(speedData, start);
}
);
}
// Draw a polyline segment (up to 100 road segments) color-coded by speed limit.
function processSpeedLimitResponse(speedData, start) {
var end = start + speedData.speedLimits.length;
for (var i = 0; i < speedData.speedLimits.length - 1; i++) {
var speedLimit = speedData.speedLimits[i].speedLimit;
var color = getColorForSpeed(speedLimit);
// Take two points for a single-segment polyline.
var coords = snappedCoordinates.slice(start + i, start + i + 2);
var snappedPolyline = new google.maps.Polyline({
path: coords,
strokeColor: color,
strokeWeight: 6
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
}
}
function getColorForSpeed(speed_kph) {
if (speed_kph <= 40) {
return 'purple';
}
if (speed_kph <= 50) {
return 'blue';
}
if (speed_kph <= 60) {
return 'green';
}
if (speed_kph <= 80) {
return 'yellow';
}
if (speed_kph <= 100) {
return 'orange';
}
return 'red';
}
$(window).load(initialize);
</script>
</head>
<body>
<div id="map"></div>
<div id="bar">
<p class="auto"><input type="text" id="autoc"/></p>
<p><a id="clear" href="#">Click here</a> to clear map.</p>
</div>
</body>
</html>
In the script that loads the JS api
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places&key=your_api_key"></script>
and for Web Services
https://roads.googleapis.com/v1/speedLimits?parameters&key=YOUR_API_KEY

set start and end position in google roads API using javascript

I want to know if setting start and end location in the map while I'm retrieving coordinates and placeId through google roads API is possible or not? Because while I initialize Roads API by setting a custom coordinate like:
var mapOptions = {
zoom: 17,
center: {lat: -33.8667, lng: 151.1955}
};
its shows me a specific location in the map where the coordinate exists. But I want to initialize a map where I set a start and end location in the map and then start to use snapToRoads API to retrieve coordinates.
Ok, I have done a little bit digging and solved it by myself.
The Javascript Part:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places"></script>
<!--Elevation JS
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>-->
<script>
//GOOGLE_API_KEY
var apiKey = 'GOOGLE_API_KEY';
alert("Provide GOOGLE API KEY");
var map;
var elevator;
var directionsDisplay;
var directionsService;
var drawingManager;
var placeIdArray = [];
var polylines = [];
var snappedCoordinates = [];
var initialLocation;
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag = new Boolean();
function initialize()
{
var mapOptions = {
zoom: 17,
center: {lat: -33.8667, lng: 151.1955}
};
directionsService = new google.maps.DirectionsService();
var polylineOptionsActual = new google.maps.Polyline({
strokeColor: '#FF0000',
strokeOpacity: 0.6,
strokeWeight: 2
});
directionsDisplay = new google.maps.DirectionsRenderer({polylineOptions: polylineOptionsActual});
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
// Create an ElevationService
elevator = new google.maps.ElevationService();
// Adds a Places search box. Searching for a place will center the map on that
// location.
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(
document.getElementById('bar'));
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocStart'));
autocomplete.bindTo('bounds', map);
autocomplete.addListener('place_changed', function() {
var placeStart = autocomplete.getPlace();
//alert(placeStart.place_id);
document.getElementById("startPlaceId").value=placeStart.place_id;
});
var autocomplete1 = new google.maps.places.Autocomplete(document.getElementById('autocEnd'));
autocomplete1.bindTo('bounds', map);
autocomplete1.addListener('place_changed', function() {
var placeEnd = autocomplete1.getPlace();
//alert(placeEnd.place_id);
document.getElementById("endPlaceId").value=placeEnd.place_id;
});
// Enables the polyline drawing control. Click on the map to start drawing a
// polyline. Each click will add a new vertice. Double-click to stop drawing.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYLINE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYLINE
]
},
polylineOptions: {
strokeColor: '#696969',
strokeWeight: 2
}
});
drawingManager.setMap(map);
// Snap-to-road when the polyline is completed.
drawingManager.addListener('polylinecomplete', function(poly) {
var path = poly.getPath();
polylines.push(poly);
placeIdArray = [];
runSnapToRoad(path);
});
// Clear button. Click to remove all polylines.
$('#clear').click(function(ev) {
for (var i = 0; i < polylines.length; ++i) {
polylines[i].setMap(null);
}
polylines = [];
ev.preventDefault();
return false;
});
}
// Snap a user-created polyline to roads and draw the snapped path
function runSnapToRoad(path) {
var pathValues = [];
for (var i = 0; i < path.getLength(); i++) {
pathValues.push(path.getAt(i).toUrlValue());
}
$.get('https://roads.googleapis.com/v1/snapToRoads', {
interpolate: true,
key: apiKey,
path: pathValues.join('|')
}, function(data) {
processSnapToRoadResponse(data);
drawSnappedPolyline();
//getAndDrawSpeedLimits();
});
}
// Store snapped polyline returned by the snap-to-road method.
function processSnapToRoadResponse(data)
{
snappedCoordinates = [];
placeIdArray = [];
for (var i = 0; i < data.snappedPoints.length; i++)
{
var latlng = new google.maps.LatLng(
data.snappedPoints[i].location.latitude,
data.snappedPoints[i].location.longitude);
//getElevation(latlng);
snappedCoordinates.push(latlng);
placeIdArray.push(data.snappedPoints[i].placeId);
}
//get Altitude in meters
getElevation(snappedCoordinates);
document.getElementById("snappedCoordinatesArray").value=snappedCoordinates;
document.getElementById("snappedPaceIdArray").value=placeIdArray;
}
// Draws the snapped polyline (after processing snap-to-road response).
function drawSnappedPolyline() {
var snappedPolyline = new google.maps.Polyline({
path: snappedCoordinates,
strokeColor: 'black',
strokeWeight: 3
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
}
// Gets speed limits (for 100 segments at a time) and draws a polyline
// color-coded by speed limit. Must be called after processing snap-to-road
// response.
function getAndDrawSpeedLimits() {
for (var i = 0; i <= placeIdArray.length / 100; i++) {
// Ensure that no query exceeds the max 100 placeID limit.
var start = i * 100;
var end = Math.min((i + 1) * 100 - 1, placeIdArray.length);
drawSpeedLimits(start, end);
}
}
// Gets speed limits for a 100-segment path and draws a polyline color-coded by
// speed limit. Must be called after processing snap-to-road response.
function drawSpeedLimits(start, end) {
var placeIdQuery = '';
for (var i = start; i < end; i++) {
placeIdQuery += '&placeId=' + placeIdArray[i];
}
$.get('https://roads.googleapis.com/v1/speedLimits',
'key=' + apiKey + placeIdQuery,
function(speedData) {
processSpeedLimitResponse(speedData, start);
}
);
}
// Draw a polyline segment (up to 100 road segments) color-coded by speed limit.
function processSpeedLimitResponse(speedData, start) {
var end = start + speedData.speedLimits.length;
for (var i = 0; i < speedData.speedLimits.length - 1; i++) {
var speedLimit = speedData.speedLimits[i].speedLimit;
var color = getColorForSpeed(speedLimit);
// Take two points for a single-segment polyline.
var coords = snappedCoordinates.slice(start + i, start + i + 2);
var snappedPolyline = new google.maps.Polyline({
path: coords,
strokeColor: color,
strokeWeight: 6
});
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
//passDataToObjC();
}
}
function getColorForSpeed(speed_kph) {
if (speed_kph <= 40) {
return 'purple';
}
if (speed_kph <= 50) {
return 'blue';
}
if (speed_kph <= 60) {
return 'green';
}
if (speed_kph <= 80) {
return 'yellow';
}
if (speed_kph <= 100) {
return 'orange';
}
return 'red';
}
function getElevation(snappedCoordinatesArr)
{
var locations = [];
// Retrieve the latlng and push it on the array
for (var i = 0; i < snappedCoordinatesArr.length; i++)
{
locations.push(snappedCoordinatesArr[i]);
}
// Create a LocationElevationRequest object using the array's one value
var positionalRequest =
{
'locations': locations
}
//alert(positionalRequest);
// Initiate the location request
elevator.getElevationForLocations(positionalRequest, function(results, status)
{
if (status == google.maps.ElevationStatus.OK)
{
// Retrieve the first result
if (results)
{
var altitudeArr=[];
for(var j=0;j<results.length;j++)
{
altitudeArr.push(results[j].elevation);
}
document.getElementById("altitudeArray").value=altitudeArr;
document.getElementById("dataDisplay").style.display="block";
//alert(altitudeArr);
}
else
{
alert('No results found');
}
}
else
{
alert('Elevation service failed due to: ' + status);
}
});
}
function calcRoute()
{
var start = document.getElementById("autocStart").value;
var end = document.getElementById('autocEnd').value;
//alert(start);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
$(window).load(initialize);
</script>
And The HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Roads API</title>
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#bar {
width: 240px;
background-color: rgba(255, 255, 255, 0.75);
margin: 8px;
padding: 4px;
border-radius: 4px;
}
#autoc {
width: 98%;
box-sizing: border-box;
}
</style>
<body>
<div id="map"></div>
<div id="bar">
<form id="geodata-form" action="http://wayzme.sulavmart.com/map/savedata">
<div id="dataDisplay" style="display:none;">
CoordinatesArray:
<input type="text" id="snappedCoordinatesArray" />
AltitudeArray:
<input type="text" id="altitudeArray" />
PaceIdArray:
<input type="text" id="snappedPaceIdArray" />
<input type="hidden" id="startPlaceId" />
<input type="hidden" id="endPlaceId" />
</div>
<p class="auto">
<input type="text" id="autocStart" style="width:98% !important" name="start" />
</p>
<p class="auto">
<input type="text" id="autocEnd" style="width:98% !important" name="end"/>
</p>
<input type="button" value="Get Directions" onClick="calcRoute();">
</form>
<p><a id="clear" href="#">Click here</a> to clear map.</p>
</div>
</body>
</html>

Google Maps not showing up in DIV

I have a web page that is used for mapping an area and determining whether or not addresses or points lie within the designated region but for some reason its not showing up any longer, where it once worked fine, it recently stopped and I dont think any changes have recently been made. Here is my code:
index.php:
<?php
include "polygon.php";
$location=null;
$location_name=null;
$loc=null;
if (isset($_GET['location_id']) && isset($_GET['location'])){
$location=$_GET['location_id'];
$location_name=$_GET['location'];
$loc = Polygon::getLocation($location_name);
}
if (isset($_POST['location_id']) && isset($_POST['location'])){
$location=$_POST['location_id'];
$location_name=$_POST['location'];
$loc = Polygon::getLocation($location_name);
}
if (!empty($_POST)) {
Polygon::saveCoords ($_POST['coords'], $location);
}
$data = Polygon::getCoords($location);
$coords = null;
if(false!=$data) {
// parse data
preg_match_all('/\((.*?)\)/', $data, $matches);
$coords= $matches[1];
}
?>
<!DOCTYPE>
<html>
<head>
<title>DP Dough Delivery Area</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/polygon.js"></script>
<script type="text/javascript">
$(function(){
// create map
<?php
if ($loc!=null){
echo 'var mapCenter=new google.maps.LatLng('.$loc['lat'].','.$loc['lng'].');';
} else {
echo 'var mapCenter=new google.maps.LatLng(38.989697,-76.93776);';
}
echo $loc['lat'].','.$loc['lng'];
?>
var myOptions = {
zoom: 12,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('main-map'), myOptions);
// holds verification addresses
var verifiedAddresses = new Array();
// now create geocoder for address<->lat/long
var geocoder = new google.maps.Geocoder();
// attached a polygon creator drawer to the map
var creator = new PolygonCreator(map);
// address as point button
$('#addAddress').click(function(){
var address = document.getElementById("addressInput").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//map.setCenter(results[0].geometry.location);
creator.pen.draw(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
// address as point button
$('#checkAddress').click(function(){
var address = document.getElementById("checkAddressInput").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
verifiedAddresses.push(marker);
if(null==creator.showData()){
$('#dataPanel').append('Please first create a polygon');
}else{
data = creator.getPoints();
//alert(data);
var paths=creator.getPoly().getPlots();
var pt = paths.getAt(0);
var numPaths = pt.getLength();
var j=0;
var oddNodes = false;
var x = results[0].geometry.location.lng();
var y = results[0].geometry.location.lat();
for (var i=0; i < numPaths; i++) {
j++;
if (j == numPaths) {j = 0;}
if (((pt.getAt(i).lat() < y) && (pt.getAt(j).lat() >= y))
|| ((pt.getAt(j).lat() < y) && (pt.getAt(i).lat() >= y))) {
if ( pt.getAt(i).lng() + (y - pt.getAt(i).lat())
/ (pt.getAt(j).lat()-pt.getAt(i).lat())
* (pt.getAt(j).lng() - pt.getAt(i).lng())<x ) {
oddNodes = !oddNodes
}
}
}
if(oddNodes == true) {
alert("Address is VALID");
$('#dataPanel').append(address+': VALID ADDRESS');
} else {
alert("Address is INVALID");
$('#dataPanel').append(address+': INVALID ADDRESS');
}
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
// reset button
$('#reset').click(function(){
creator.destroy();
creator=null;
creator=new PolygonCreator(map);
$.each(verifiedAddresses, function(index, value){
value.setMap(null);
});
verifiedAddresses =null;
verifiedAddresses =new Array();
verifiedAddresses.length=0;
});
// set polygon data to the form hidden field
$('#map-form').submit(function () {
$('#map-coords').val(creator.showData());
});
//show coords
$('#showData').click(function(){
$('#dataPanel').empty();
if(null==creator.showData()){
$('#dataPanel').append('Please first create a polygon');
}else{
$('#dataPanel').append(creator.showData());
}
});
//show color
$('#showColor').click(function(){
$('#dataPanel').empty();
if(null==creator.showData()){
$('#dataPanel').append('Please first create a polygon');
}else{
$('#dataPanel').append(creator.showColor());
}
});
<?php if (null!=$coords): ?>
// create
var polygonCoords = [<?php
foreach ( $coords as $i=>$coord ):
echo 'new google.maps.LatLng('.$coord.')';
if ( $i<=count($coords)) {
echo ',';
}
endforeach;?>];
$.each(polygonCoords, function(index, value){
creator.pen.draw(value);
});
// construct the polygon
polygon = new google.maps.Polygon({
paths: polygonCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
});
// show polygon on the map
polygon.setMap(map);
<?php endif;?>
});
</script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="header">
<p>
<span class="instruction">Instructions:</span>
Left click on the map to create markers, when last marker meets first marker, it will form a polygon.
Right click on the polygon to change its hex value color.
</p>
</div>
<div id="main-map">
</div>
<div id="side">
<input id="addressInput" placeholder="Add Address As Point " type="text" class="navi"/>
<input id="addAddress" value="Add Address As Point" type="button" class="navi"/>
<input id="checkAddressInput" placeholder="Verify Address " type="text" class="navi"/>
<input id="checkAddress" value="Verify Address" type="button" class="navi"/>
<input id="reset" value="Reset" type="button" class="navi"/>
<input id="showData" value="Show Data Points " type="button" class="navi"/>
<input id="showColor" value="Show Color " type="button" class="navi"/>
<div id="dataPanel">
</div>
</div>
<form action="index.php" method="POST" id="map-form">
<input type="hidden" name="coords" id="map-coords" value=""/>
<input type="hidden" name="location_id" id="location_id" value="<?php echo $location; ?>"/>
<input type="hidden" name="location" id="location" value="<?php echo $location_name; ?>"/>
<input type="submit" name="save" value="Save"/>
<input type="button" value="Reset" id="reset"/>
</form>
</body>
</html>
style.css:
html,body{
margin:0;
padding:0;
width:100%;
height:100%;
font-family:Arial, Helvetica, sans-serif;
}
div#header{
vertical-align:middle;
border-bottom:1px solid #000;
}
div#main-map{
width:70%;
height:70%;
float:left;
}
div#side{
width:30%;
float:left;
}
div#dataPanel{
width:90%;
height:50%;
overflow:auto;
border:2px solid #DDDDDD;
}
div#side input{
width:90%;
}
div#side input.navi{
font-size:18px;
height:30px;
margin-bottom:10px;
}
div ul{
margin-top:30px;
margin-bottom:30px;
}
div ul li{
display: inline;
list-style-type: none;
padding-right: 40px;
font-size:18px;
font-weight:bold;
}
div ul li.title{
font-size:22px;
color:#888;
}
div#header p{
color:#888;
font-size:14px;
padding-left:20px;
}
span.instruction{
font-weight:bold;
}
.message-box { text-align: center; padding: 5px; color:#545454; width:80%; margin:5px auto; font-size:12px;}
.clean { background-color: #efefef; border-top: 2px solid #dedede; border-bottom: 2px solid #dedede; }
.info { background-color: #f7fafd; border-top: 2px solid #b5d3ff; border-bottom: 2px solid #b5d3ff; }
.ok { background-color: #d7f7c4; border-top: 2px solid #82cb2f; border-bottom: 2px solid #82cb2f; }
.alert { background-color: #fef5be; border-top: 2px solid #fdd425; border-bottom: 2px solid #fdd425; }
.error { background-color: #ffcdd1; border-top: 2px solid #e10c0c; border-bottom: 2px solid #e10c0c; }
polygon.php:
<?php
class Polygon
{
static $_dbHost = 'localhost';
static $_dbName = 'database';
static $_dbUserName = 'root';
static $_dbUserPwd = 'password';
static private $url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=";
static public function getLocation($address){
$url = self::$url.urlencode($address);
$resp_json = self::curl_file_get_contents($url);
$resp = json_decode($resp_json, true);
if($resp['status']='OK'){
return $resp['results'][0]['geometry']['location'];
}else{
return false;
}
}
static public function getLocationURL($address){
$url = self::$url.urlencode($address);
return $url;
}
static private function curl_file_get_contents($URL){
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
// get coordinates
static public function getCoords($location)
{
if ($location == null) return FALSE;
return self::get($location);
}
// save coordinates
static public function saveCoords($rawData, $location)
{
self::save($rawData, $location);
}
static public function getLocationAddress($city)
{
$data=false;
if ($city!=null && $city!=""){
$link = mysqli_connect("localhost", "root", "password", "database");
if ($stmt = $link->prepare("SELECT address FROM tbl_location_data WHERE city=?")) {
/* bind parameters for markers */
$sql= "SELECT address FROM tbl_location_data WHERE city=\"$city\"";
if ($result = $link->query($sql)) {
while($obj = $result->fetch_object()){
$data=$obj->address;
}
return $data;
} else {
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($data);
/* fetch value */
$stmt->fetch();
/* close statement */
if ($stmt->num_rows <= 0)
{
$stmt->close();
return FALSE;
}
$stmt->close();
}
}
return $data;
}
}
// save lat/lng to database
static public function save ($data, $location)
{
if($location!=null && !self::locationExists($location)){
$link = mysqli_connect("localhost", "root", "password", "database");
/* Create the prepared statement */
if ($stmt = $link->prepare("INSERT INTO points (location_id, data) values (?, ?)")) {
/* Bind our params */
$stmt->bind_param('ss', $location, $data);
/* Execute the prepared Statement */
$stmt->execute();
/* Echo results */
echo "Inserted data into database<br>";
/* Close the statement */
$stmt->close();
}
else {
/* Error */
printf("Prepared Statement INSERT Error: %s\n", $mysqli->error);
}
} else if ($location!=null && self::locationExists($location)){
$link = mysqli_connect("localhost", "root", "password", "database");
/* Create the prepared statement */
if ($stmt = $link->prepare("UPDATE points SET data=? WHERE location_id=?")) {
/* Bind our params */
$stmt->bind_param('ss', $data, $location);
/* Execute the prepared Statement */
$stmt->execute();
/* Echo results */
echo "UPDATED {$location},<br>{$data}<br> into database\n";
/* Close the statement */
$stmt->close();
}
else {
/* Error */
printf("Prepared Statement UPDATE Error: %s\n", $mysqli->error);
}
}
}
static private function locationExists($location){
$link = mysqli_connect("localhost", "root", "password", "database");
/* Create the prepared statement */
if ($stmt = $link->prepare("SELECT id FROM points WHERE location_id = ?")) {
/* Bind our params */
$stmt->bind_param('s', $location);
/* Execute the prepared Statement */
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id);
$stmt->fetch();
if ($stmt->num_rows > 0)
{
$stmt->close();
return TRUE;
}
$stmt->close();
return FALSE;
}
}
// get lat/lng from database
static private function get($location)
{
$data = false;
$link = mysqli_connect("localhost", "root", "password", "database");
/* Create the prepared statement */
if ($stmt = $link->prepare("SELECT data FROM points WHERE location_id=?")) {
/* bind parameters for markers */
$sql= "SELECT id,data FROM points WHERE location_id=\"$location\"";
if ($result = $link->query($sql)) {
while($obj = $result->fetch_object()){
$data=$obj->data;
}
return $data;
} else {
$stmt->bind_param("s", $location);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($data);
/* fetch value */
$stmt->fetch();
/* close statement */
if ($stmt->num_rows <= 0)
{
$stmt->close();
return FALSE;
}
$stmt->close();
}
}
return $data;
}
}
polygon.js:
function PolygonCreator(map){
//create pen to draw on map
this.map = map;
this.pen = new Pen(this.map);
var thisOjb=this;
this.event=google.maps.event.addListener(thisOjb.map, 'click', function(event) {
thisOjb.pen.draw(event.latLng);
});
this.showData = function(){
return this.pen.getData();
}
this.getPoints = function(){
return this.pen.getPlots();
}
this.showColor = function(){
return this.pen.getColor();
}
this.getPoly = function() {
return this.pen.getPolygon();
}
//destroy the pen
this.destroy = function(){
this.pen.deleteMis();
if(null!=this.pen.polygon){
this.pen.polygon.remove();
}
google.maps.event.removeListener(this.event);
}
}
/*
* pen class
*/
function Pen(map){
this.map= map;
this.listOfDots = new Array();
this.polyline =null;
this.polygon = null;
this.currentDot = null;
//draw function
this.draw = function(latLng){
if (null != this.polygon) {
alert('Click Reset to draw another');
}else {
if (this.currentDot != null && this.listOfDots.length > 1 && this.currentDot == this.listOfDots[0]) {
this.drawPolygon(this.listOfDots);
}else {
//remove previous line
if(null!=this.polyline){
this.polyline.remove();
}
//draw Dot
var dot = new Dot(latLng, this.map, this);
this.listOfDots.push(dot);
//draw line
if(this.listOfDots.length > 1){
this.polyline = new Line(this.listOfDots, this.map);
}
}
}
}
//draw ploygon
this.drawPolygon = function (listOfDots,color,des,id){
this.polygon = new Polygon(listOfDots,this.map,this,color,des,id);
this.deleteMis();
}
//return polygon
this.getPolygon = function () {
return this.polygon;
}
//delete all dots and polylines
this.deleteMis = function(){
//delete dots
$.each(this.listOfDots, function(index, value){
value.remove();
});
this.listOfDots.length=0;
//delete lines
if(null!=this.polyline){
this.polyline.remove();
this.polyline=null;
}
}
//cancel
this.cancel = function(){
if(null!=this.polygon){
(this.polygon.remove());
}
this.polygon=null;
this.deleteMis();
}
//setter
this.setCurrentDot = function(dot){
this.currentDot = dot;
}
//getter
this.getListOfDots = function(){
return this.listOfDots;
}
//get plots data
this.getData = function(){
if(this.polygon!=null){
var data ="";
var paths = this.polygon.getPlots();
//get paths
paths.getAt(0).forEach(function(value, index){
data+=(value.toString());
});
return data;
}else {
return null;
}
}
//get plots data
this.getPlots = function(){
if(this.polygon!=null){
var paths = this.polygon.getPlots();
return paths;
}else {
return null;
}
}
//get color
this.getColor = function(){
if(this.polygon!=null){
var color = this.polygon.getColor();
return color;
}else {
return null;
}
}
}
/* Child of Pen class
* dot class
*/
function Dot(latLng,map,pen){
//property
this.latLng=latLng;
this.parent = pen;
this.markerObj = new google.maps.Marker({
position: this.latLng,
map: map
});
//closure
this.addListener = function(){
var parent=this.parent;
var thisMarker=this.markerObj;
var thisDot=this;
google.maps.event.addListener(thisMarker, 'click', function() {
parent.setCurrentDot(thisDot);
parent.draw(thisMarker.getPosition());
});
}
this.addListener();
//getter
this.getLatLng = function(){
return this.latLng;
}
this.getMarkerObj = function(){
return this.markerObj;
}
this.remove = function(){
this.markerObj.setMap(null);
}
}
/* Child of Pen class
* Line class
*/
function Line(listOfDots,map){
this.listOfDots = listOfDots;
this.map = map;
this.coords = new Array();
this.polylineObj=null;
if (this.listOfDots.length > 1) {
var thisObj=this;
$.each(this.listOfDots, function(index, value){
thisObj.coords.push(value.getLatLng());
});
this.polylineObj = new google.maps.Polyline({
path: this.coords,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
map: this.map
});
}
this.remove = function(){
this.polylineObj.setMap(null);
}
}
/* Child of Pen class
* polygon class
*/
function Polygon(listOfDots,map,pen,color){
this.listOfDots = listOfDots;
this.map = map;
this.coords = new Array();
this.parent = pen;
this.des = 'Hello';
var thisObj=this;
$.each(this.listOfDots,function(index,value){
thisObj.coords.push(value.getLatLng());
});
this.polygonObj= new google.maps.Polygon({
paths: this.coords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map:this.map
});
this.remove = function(){
this.info.remove();
this.polygonObj.setMap(null);
}
//getter
this.getContent = function(){
return this.des;
}
this.getPolygonObj= function(){
return this.polygonObj;
}
this.getListOfDots = function (){
return this.listOfDots;
}
this.getPlots = function(){
return this.polygonObj.getPaths();
}
this.getColor=function(){
return this.getPolygonObj().fillColor;
}
//setter
this.setColor = function(color){
return this.getPolygonObj().setOptions(
{fillColor:color,
strokeColor:color,
strokeWeight: 2
}
);
}
this.info = new Info(this,this.map);
//closure
this.addListener = function(){
var info=this.info;
var thisPolygon=this.polygonObj;
google.maps.event.addListener(thisPolygon, 'rightclick', function(event) {
info.show(event.latLng);
});
}
this.addListener();
}
/*
* Child of Polygon class
* Info Class
*/
function Info(polygon,map){
this.parent = polygon;
this.map = map;
this.color = document.createElement('input');
this.button = document.createElement('input');
$(this.button).attr('type','button');
$(this.button).val("Change Color");
var thisOjb=this;
//change color action
this.changeColor= function(){
thisOjb.parent.setColor($(thisOjb.color).val());
}
//get content
this.getContent = function(){
var content = document.createElement('div');
$(this.color).val(this.parent.getColor());
$(this.button).click(function(){
thisObj.changeColor();
});
$(content).append(this.color);
$(content).append(this.button);
return content;
}
thisObj=this;
this.infoWidObj = new google.maps.InfoWindow({
content:thisObj.getContent()
});
this.show = function(latLng){
this.infoWidObj.setPosition(latLng);
this.infoWidObj.open(this.map);
}
this.remove = function(){
this.infoWidObj.close();
}
}
i know its a lot of code but it works very simply. the get parameters in index.php contains a location to center the map and a location id to grab the polygon points from the database. the polygon is then created and overlayed on the map and addresses are checked for being validly contained within the polygons area or invalid outside of the polygons area. the problem is that the map is not showing up in the main-map div and i have no idea why this stopped working, someone may have made changes to the code but i can't seem to find any and it was working fine last time i made any edits.
it was foolish mistake, i didn't notice that the server admin had forced https and i was grabbing the scripts over http. i'll leave this code as it may be useful for someone else. thank you

issue with click event in nokia maps api

i try this code
for(i=0; i<num ;i++)
{
points.push([lats[i], lngs[i]]);
if(i==0) str = 'S';
else if(i==num-1) str = 'E';
else str = '';
var marker = new nokia.maps.map.Marker(
[lats[i], lngs[i]],
{
title: str,
visibility: true,
icon: img,
anchor: new nokia.maps.util.Point(5, 5)
});
marker.addListener('click', function(evt){
$('.loc').html(times[i]);
});
map.objects.add(marker);
}
but it just does not fire click event. is anything wrong with code?
lats and lngs and times are defined and points is to be used later.
Edit:
Problem solved. See comment for answer below.
It looks like the problem is with the line:
$('.loc').html(times[i]);
Within the marker listener. The event hasn't got access to the array element when it is fired and therefore fails. I think you need to add an attribute to the marker and access it as shown:
var marker = new nokia.maps.map.Marker(
[lats[i], lngs[i]],
{
title: str,
visibility: true,
icon: img,
anchor: new nokia.maps.util.Point(29, 71),
$html : times[i]
});
marker.addListener('click', function(evt){
//$('.loc').html(times[i]);
alert (evt.target.$html);
});
Try the following (with your own App Id and token of course):
<!DOCTYPE HTML SYSTEM>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9" />
<script type="text/javascript" charset="UTF-8" src="http://api.maps.nokia.com/2.2.3/jsl.js"></script>
<style type="text/css">
html {
overflow:hidden;
}
body {
margin: 0;
padding: 0;
overflow: hidden;
width: 100%;
height: 100%;
position: absolute;
}
#mapContainer {
width:100%;
height: 100%;
left: 0;
top: 0;
position: absolute;
}
</style>
</head>
<body>
<div id="mapContainer"></div>
<script type="text/javascript">
nokia.Settings.set( "appId", "YOUR APP ID GOES HERE");
nokia.Settings.set( "authenticationToken", "YOUR AUTHENTICATION TOKEN GOES HERE");
var mapContainer = document.getElementById("mapContainer");
var DefaultLatitude = 52.516237;
var DefaultLongitude = 13.377686;
var defaultZoomLevel = 16;
var mapOptions =
{
baseMapType: nokia.maps.map.Display.NORMAL,
center: new nokia.maps.geo.Coordinate(DefaultLatitude, DefaultLongitude),
zoomLevel: defaultZoomLevel,
components: [
new nokia.maps.map.component.ZoomBar(),
new nokia.maps.map.component.Behavior(),
new nokia.maps.map.component.Overview(),
new nokia.maps.map.component.ScaleBar(),
new nokia.maps.map.component.ContextMenu()
]
};
var map = new nokia.maps.map.Display(mapContainer, mapOptions);
var str ="";
var img = "http://api.maps.nokia.com/en/playground/examples/maps/res/markerHouse.png";
var points= new Array();
var lats = new Array();
var lngs = new Array();
var times = new Array();
var num;
lats[0] = 52.516237;
lngs[0] = 13.377686;
times[0] = "brandenburg gate";
num = 1;
for(var i=0; i<num ;i++)
{
points.push([lats[i], lngs[i]]);
if(i==0) str = 'S';
else if(i==num-1) str = 'E';
else str = '';
var marker = new nokia.maps.map.Marker(
[lats[i], lngs[i]],
{
title: str,
visibility: true,
icon: img,
anchor: new nokia.maps.util.Point(29, 71),
$html : times[i]
});
marker.addListener('click', function(evt){
//$('.loc').html(times[i]);
alert (evt.target.$html);
});
map.objects.add(marker);
}
</script>
</body>
</html>

Categories

Resources