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
Related
I wanted to create custom "HTMLMarker" for google maps, but I just found out, it is not displaying in the street view. I have searched docs, but nothing is written there. (Googled: "show OverlayView marker in street view")
interface HTMLMarkerOptions {
position: google.maps.LatLng | google.maps.LatLngLiteral;
content: HTMLElement;
}
class HTMLMarker extends google.maps.OverlayView {
private _element: HTMLElement;
private _isAppended = false;
private _position: google.maps.LatLng;
constructor(options: HTMLMarkerOptions) {
super();
this._position = this._createLatLng(options.position)
this._element = document.createElement('div');
this._element.style.position = 'absolute';
this._element.appendChild(options.content);
}
_appendDivToOverlay() {
const panes = this.getPanes();
panes.overlayMouseTarget.appendChild(this._element);
this._isAppended = true;
}
_positionDiv() {
const map = this.getMap();
if (map instanceof google.maps.StreetViewPanorama) {
// TODO: Render in StreetView
return;
} else {
const projection = this.getProjection();
const point = projection.fromLatLngToDivPixel(this._position);
if (point) {
this._element.style.left = `${point.x - this._offset.left}px`;
this._element.style.top = `${point.y - this._offset.top}px`;
}
}
}
setMap(map: google.maps.Map | google.maps.StreetViewPanorama | null) {
super.setMap(map);
}
draw() {
if (!this._isAppended) {
this._appendDivToOverlay();
}
this._positionDiv();
}
remove(): void {
this._element.parentNode?.removeChild(this._element);
this._isAppended = false;
}
setPosition(position: google.maps.LatLng | google.maps.LatLngLiteral): void {
if (!this._LatLngEquals(this._position, position)) {
this._position = this._createLatLng(position);
}
}
getPosition(): google.maps.LatLng {
return this._position;
}
getDraggable(): boolean {
return false;
}
private _createLatLng(
position: google.maps.LatLng | google.maps.LatLngLiteral,
): google.maps.LatLng {
if (position instanceof google.maps.LatLng) {
return position;
} else {
return new google.maps.LatLng(position);
}
}
private _LatLngEquals(
positionA: google.maps.LatLng | undefined,
positionB: google.maps.LatLng | google.maps.LatLngLiteral,
): boolean {
if (!positionA) {
return false;
}
if (positionB instanceof google.maps.LatLng) {
return positionA.equals(positionB);
} else {
return positionA.lat() == positionB.lat && positionA.lng() == positionB.lng;
}
}
}
example fiddle (compiled TS to ESNext)
Although the documentation says:
Additionally, when creating a map with a default StreetViewPanorama, any markers created on a map are shared automatically with the map's associated Street View panorama, provided that panorama is visible.
That doesn't seem to be true for the HTMLMarker. Setting the map property of the HTMLMarker to the default Street View panorama of the map:
marker.setMap(map.getStreetView());
makes it visible.
proof of concept fiddle
Related question: Drawing polylines on Google Maps Streetview
code snippet:
const map = new google.maps.Map(
document.querySelector('#map-canvas'), {
zoom: 18,
center: new google.maps.LatLng(37.422, -122.084),
mapTypeId: google.maps.MapTypeId.ROADMAP,
},
);
google.maps.event.addListener(map, 'click', function(e) {
console.log(e.latLng.toUrlValue(6));
})
class HTMLMarker extends google.maps.OverlayView {
constructor(options) {
super();
this._isAppended = false;
this._position = this._createLatLng(options.position);
this._element = document.createElement('div');
this._element.style.position = 'absolute';
this._element.appendChild(options.content);
}
_appendDivToOverlay() {
const panes = this.getPanes();
panes.overlayMouseTarget.appendChild(this._element);
this._isAppended = true;
}
_positionDiv() {
const map = this.getMap();
const projection = this.getProjection();
const point = projection.fromLatLngToDivPixel(this._position);
if (point) {
this._element.style.left = point.x + 'px';
this._element.style.top = point.y + 'px';
}
}
setMap(map) {
super.setMap(map);
}
draw() {
if (!this._isAppended) {
this._appendDivToOverlay();
}
this._positionDiv();
}
remove() {
if (this._element.parentNode) {
this._element.parentNode.removeChild(this._element);
}
this._isAppended = false;
}
setPosition(position) {
if (!this._LatLngEquals(this._position, position)) {
this._position = this._createLatLng(position);
}
}
getPosition() {
return this._position;
}
getDraggable() {
return false;
}
_createLatLng(position) {
if (position instanceof google.maps.LatLng) {
return position;
} else {
return new google.maps.LatLng(position);
}
}
_LatLngEquals(positionA, positionB) {
if (!positionA) {
return false;
}
if (positionB instanceof google.maps.LatLng) {
return positionA.equals(positionB);
} else {
return positionA.lat() == positionB.lat && positionA.lng() == positionB.lng;
}
}
}
const marker = new HTMLMarker({
position: new google.maps.LatLng(37.42197, -122.083627),
content: document.querySelector('#marker'),
});
marker.setMap(map);
const marker1 = new google.maps.Marker({
position: new google.maps.LatLng(37.42197, -122.083627),
});
marker1.setMap(map);
// We get the map's default panorama and set up some defaults.
// Note that we don't yet set it visible.
panorama = map.getStreetView();
panorama.setPosition({
lat: 37.421885,
lng: -122.083662
});
panorama.setPov( /** #type {google.maps.StreetViewPov} */ ({
heading: 0,
pitch: 0
}));
panorama.setVisible(true);
panorama.setZoom(1);
marker.setMap(map.getStreetView());
* {
box-sizing: border-box;
}
body {
margin: 0;
}
#map-canvas {
height: 100vh;
width: 100vw;
background-color: #CCC;
}
#marker {
display: flex;
height: 50px;
width: 50px;
background: white;
border: 3px solid black;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas"></div>
<div id="marker">
ID: 1
</div>
I also had a look at this yesterday and as mentioned by geocodezip, the documentation is misleading (or wrong). It mentions that
if you explicitly set the map's streetView property to a StreetViewPanorama of your own construction, you will override the default panorama and disable automatic overlay sharing
which to me would mean that if you are not using a panorama of your own construction (and therefore the default panorama), overlay sharing should work, unless if by "overlay" they meant Marker.
Here is a proof that a standard Marker is shared between the map and the default panorama without the need to do anything and the custom overlay isn't:
var map;
var panorama;
var htmlMarker;
function initialize() {
function HTMLMarker(lat, lng) {
this.lat = lat;
this.lng = lng;
this.pos = new google.maps.LatLng(lat, lng);
this.divReference = null;
}
HTMLMarker.prototype = new google.maps.OverlayView();
HTMLMarker.prototype.onRemove = function() {
this.divReference.parentNode.removeChild(this.divReference);
this.divReference = null;
}
HTMLMarker.prototype.onAdd = function() {
div = document.createElement('DIV');
div.className = "html-marker";
div.style.width = '60px';
div.style.height = '50px';
div.innerHTML = 'ABC';
var panes = this.getPanes();
panes.overlayMouseTarget.appendChild(div);
this.divReference = div;
}
HTMLMarker.prototype.draw = function() {
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
var panes = this.getPanes();
panes.overlayMouseTarget.style.left = position.x - 30 + 'px';
panes.overlayMouseTarget.style.top = position.y - 25 + 'px';
}
// Set up the map
var mapOptions = {
center: new google.maps.LatLng(40.729884, -73.990988),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
panorama = map.getStreetView();
panorama.setPosition(new google.maps.LatLng(40.729884, -73.990988));
panorama.setPov({
heading: 330,
zoom: 1,
pitch: 0
});
htmlMarker = new HTMLMarker(40.729952, -73.991056);
htmlMarker.setMap(map);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(40.729952, -73.991198),
map: map,
draggable: true,
title: 'My marker'
});
}
function toggleStreetView() {
var toggle = panorama.getVisible();
if (toggle == false) {
panorama.setVisible(true);
} else {
panorama.setVisible(false);
}
}
var button = document.getElementsByTagName('input')[0];
button.onclick = function() {
toggleStreetView()
};
#map-canvas {
height: 150px;
}
input {
margin: 10px;
background-color: #4CAF50;
border: none;
color: white;
padding: 4px 8px;
}
.html-marker {
background-color: red;
color: white;
line-height: 50px;
text-align: center;
font-size: 18px;
font-weight: bold;
}
<input type="button" value="Toggle Street View">
<div id="map-canvas"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize" async defer></script>
And here, when changing from map to default panorama, I simply do
htmlMarker.setMap(null);
htmlMarker.setMap(panorama);
and it works.
var map;
var panorama;
var htmlMarker;
function initialize() {
function HTMLMarker(lat, lng) {
this.lat = lat;
this.lng = lng;
this.pos = new google.maps.LatLng(lat, lng);
this.divReference = null;
}
HTMLMarker.prototype = new google.maps.OverlayView();
HTMLMarker.prototype.onRemove = function() {
this.divReference.parentNode.removeChild(this.divReference);
this.divReference = null;
}
HTMLMarker.prototype.onAdd = function() {
div = document.createElement('DIV');
div.className = "html-marker";
div.style.width = '60px';
div.style.height = '50px';
div.innerHTML = 'ABC';
var panes = this.getPanes();
panes.overlayMouseTarget.appendChild(div);
this.divReference = div;
}
HTMLMarker.prototype.draw = function() {
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
var panes = this.getPanes();
panes.overlayMouseTarget.style.left = position.x - 30 + 'px';
panes.overlayMouseTarget.style.top = position.y - 25 + 'px';
}
// Set up the map
var mapOptions = {
center: new google.maps.LatLng(40.729884, -73.990988),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
panorama = map.getStreetView();
panorama.setPosition(new google.maps.LatLng(40.729884, -73.990988));
panorama.setPov({
heading: 330,
zoom: 1,
pitch: 0
});
htmlMarker = new HTMLMarker(40.729952, -73.991056);
htmlMarker.setMap(map);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(40.729952, -73.991198),
map: map,
draggable: true,
title: 'My marker'
});
}
function toggleStreetView() {
var toggle = panorama.getVisible();
if (toggle == false) {
panorama.setVisible(true);
htmlMarker.setMap(null);
htmlMarker.setMap(panorama);
} else {
panorama.setVisible(false);
htmlMarker.setMap(null);
htmlMarker.setMap(map);
}
}
var button = document.getElementsByTagName('input')[0];
button.onclick = function() {
toggleStreetView()
};
#map-canvas {
height: 150px;
}
input {
margin: 10px;
background-color: #4CAF50;
border: none;
color: white;
padding: 4px 8px;
}
.html-marker {
background-color: red;
color: white;
line-height: 50px;
text-align: center;
font-size: 18px;
font-weight: bold;
}
<input type="button" value="Toggle Street View">
<div id="map-canvas"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize" async defer></script>
I have opened a new issue in the tracker. Let's see if this is a bug in the API, or an issue with the documentation (or both).
Fiddle showing how to do it: http://jsfiddle.net/upsidown/mLa4zvs7/
Fiddle showing that overlay sharing does not work by default: http://jsfiddle.net/upsidown/xsqvm6n0/
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
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="▶" 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°<input type="range" id="tilt_level" min="40" max="130" step="5" value="40">130°<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="▶" 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
I have been working in this code, and works fine in localhost, but when I try to put this in word press the map doesn't come, and I don't know how to fix case I am new in WordPress.
A really need a hand on this, thanks
var geocoder;
function initMap() {
GeolocateUser();
var enderesso, Dest_location;
var UserLocation;
var markers = [];
var origin_place_id = null;
var destination_place_id = null;
var travel_mode = google.maps.TravelMode.DRIVING;
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
zoom: 13
});
geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
});
directionsDisplay.setMap(map);
var origin_input = document.getElementById('origin-input');
var destination_input = document.getElementById('destination-input');
var total_distance = document.getElementById('total-distance');
var total_duration = document.getElementById('total-duration');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(origin_input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(destination_input);
var origin_autocomplete = new google.maps.places.Autocomplete(origin_input);
origin_autocomplete.bindTo('bounds', map);
var destination_autocomplete = new google.maps.places.Autocomplete(destination_input);
destination_autocomplete.bindTo('bounds', map);
// On Change route action
directionsDisplay.addListener('directions_changed', function(){
total_distance.value = getDistance(directionsDisplay.getDirections());
total_duration.value = getDuration(directionsDisplay.getDirections());
});
// On click map action
map.addListener('click',function(e){
clearMarkers();
if (!UserLocation) {
UserLocation=e.latLng;
addMarker(e.latLng);
route();
}else{
Dest_location=e.latLng;
route();
}
});
origin_autocomplete.addListener('place_changed', function() {
var place = origin_autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
clearMarkers();
expandViewportToFitPlace(map, place);
// If the place has a geometry, store its place ID and route if we have
// the other place ID
origin_place_id = place.place_id;
UserLocation = place.geometry.location;
addMarker(UserLocation);
route();
});
destination_autocomplete.addListener('place_changed', function() {
var place = destination_autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
expandViewportToFitPlace(map, place);
clearMarkers();
// If the place has a geometry, store its place ID and route if we have
// the other place ID
Dest_location = place.geometry.location;
destination_place_id = place.place_id;
route();
});
function route() {
if (!UserLocation || !Dest_location) {
return;
}
clearMarkers();
directionsService.route({
origin: UserLocation ,
destination: Dest_location,
travelMode: travel_mode
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position:location,
map: map
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
//Get Distance
function getDistance(result){
var d = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
d += myroute.legs[i].distance.value;
}
d=(d/1000);
return d;
}
//Get duration
function getDuration(result){
var time = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
time += myroute.legs[i].duration.value;
}
time =(time/60)+10;
time = time.toFixed(0);
return time;
}
//Get full adress
function getAddress(latLng) {
var edress;
geocoder.geocode( {'latLng': latLng},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
adress = results[0].formatted_address;
}
else {
adress = "No results";
}
}
else {
adress = status;
}
});
return adress;
}
//Geolocate User
function GeolocateUser(){
UserLocation = new google.maps.LatLng(0.0,0.0);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
UserLocation = new google.maps.LatLng(position.coords.latitude+0, position.coords.longitude+0);
addMarker(UserLocation);
map.setCenter(UserLocation);
});
}
}
//View Point Simple
function expandViewportToFitPlace(map, place) {
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(11);
}
}
}
<!DOCTYPE html>
<html>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#origin-input,
#destination-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 200px;
}
#origin-input:focus,
#destination-input:focus {
border-color: #4d90fe;
}
#mode-selector {
color: #fff;
background-color: #4d90fe;
margin-left: 12px;
padding: 5px 11px 0px 11px;
}
#mode-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
<input id="origin-input" class="controls" type="text"
placeholder="Enter an origin location">
<input id="destination-input" class="controls" type="text"
>
<input type="text" id="total-distance" placeholder="Calculating.."/>
<input type="text" id="total-duration" placeholder="Calculating.."/>
<div id="map"></div>
<script src="main.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?signed_in=true&libraries=places&callback=initMap" async defer></script>
</html>
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>