How to combine JsFiddle into one HTML file? - jsfiddle

I am trying to put this http://jsfiddle.net/upsidown/gefg183r/
Into my website, I tried to make it work in a single file as can be seen here:
But it doesn't seem to be working in tryit editor, what am I doing wrong?
<!DOCTYPE html>
<html>
<body>
<style>
body {
font-family: Courier;
}
input {
margin-bottom: 5px;
}
#map-canvas {
height: 400px;
}
</style>
<script>
// Calculate maximum latitude value on mercator projection
var maxLat = Math.atan(Math.sinh(Math.PI)) * 180 / Math.PI;
function initialize() {
var center = new google.maps.LatLng(0, 0);
var mapOptions = {
zoom: 3,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// DOM event listener for the center map form submit
google.maps.event.addDomListener(document.getElementById('mapCenterForm'), 'submit', function(e) {
e.preventDefault();
// Get lat and lng values from input fields
var lat = document.getElementById('lat').value;
var lng = document.getElementById('lng').value;
// Validate user input as numbers
lat = (!isNumber(lat) ? 0 : lat);
lng = (!isNumber(lng) ? 0 : lng);
// Validate user input as valid lat/lng values
lat = latRange(lat);
lng = lngRange(lng);
// Replace input values
document.getElementById('lat').value = lat;
document.getElementById('lng').value = lng;
// Create LatLng object
var mapCenter = new google.maps.LatLng(lat, lng);
new google.maps.Marker({
position: mapCenter,
title: 'Marker title',
map: map
});
// Center map
map.setCenter(mapCenter);
});
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function latRange(n) {
return Math.min(Math.max(parseInt(n), -maxLat), maxLat);
}
function lngRange(n) {
return Math.min(Math.max(parseInt(n), -180), 180);
}
initialize();
</script>
<form id="mapCenterForm">
Lat:
<input type="text" id="lat" />
<br />Lng:
<input type="text" id="lng" />
<br />
<input type="submit" value="Center map" />
</form>
<br />
<div id="map-canvas" style="height:400px"></div>
</body>
</html>

Related

How can I make my WebRTC is working properly

Now I am building a video call site with WebRTC. But it recognize camera and ask to allow camera.
When I allow camera it shows nothing.
I will write down my code here.
<body onload="init()">
<div class="row">
<div class="col-8">
<form action="#">
<h5>Current Room ID: <span id="curr_room_id"></span><br/></h5>
<input id="new_room_id" name="room" type="text" placeholder="Enter a room id to connect..." style="padding: 5px"/>
<input type="submit" id="connect" value="Connect" />
</form>
<input id="call" type="submit" value="Call" disabled="true"/>
<input id="end" type="submit" value="End Call"disabled="true"/>
</div>
<div class="col-4" id="google_translate_element"></div>
</div>
<h1>local</h1>
<video id="local_video" width="400px" style="border: 1px solid black;"></video>
<h1>remote</h1>
<video id="remote_video" width="400px" style="border: 1px solid black;"></video>
<script src="/socket.io/socket.io.js"></script>
<script src="../scripts/video-client.js"></script>
<script src="../scripts/video-room.js"></script>
<script>
function init() {
console.log("document loaded");
call.removeAttribute("disabled");
call.addEventListener("click", function(){
createPeerConnection();
call.setAttribute("disabled", true);
end.removeAttribute("disabled");
});
end.addEventListener("click", function() {
// change rooms
end.setAttribute("disabled", true);
call.removeAttribute("disabled");
});
}
</script>
</body>
I think it is because of not showing video stream to webview. But i didn't find nothing. Please tell me.
And here is video-client.js
console.log("loaded");
var socket = io();
var local = document.getElementById("local_video");
var remote = document.getElementById("remote_video");
var call = document.getElementById("call");
var end = document.getElementById("end");
var room_id = document.getElementById("curr_room_id");
var localStream = null, remoteStream = null;
var config = {'iceServers' : [{'url' : 'stun:stun.l.google.com:19302'}]};
var pc;
/////////////////////////////////
function createPeerConnection() {
try {
pc = new RTCPeerConnection(config);
pc.onicecandidate = handleIceCandidate;
pc.onaddstream = handleRemoteStreamAdded;
pc.onremovestream = handleRemoteStreamRemoved;
pc.onnegotiationneeded = handleNegotiationNeeded;
getUserMedia(displayLocalVideo);
pc.addStream(localStream);
console.log("Created RTCPeerConnection");
} catch (e) {
console.log("Failed to create PeerConnection: " + e.message);
return;
}
}
function handleIceCandidate(event) {
console.log("handleIceCandidate event: " + event);
if(event.candidate) {
sendMessage(JSON.stringify({'candidate': evt.candidate}));
} else {
consolel.log("End of ice candidates");
}
}
function handleRemoteStreamAdded(event) {
console.log("Remote stream added");
displayRemoteVideo(event.stream);
call.setAttribute("disabled", true);
end.removeAttribute("disabled");
}
function handleRemoteStreamRemoved(event) {
console.log("Remote stream removed: " + event);
end.setAttribute("disabled", true);
call.removeAttribute("disabled");
local.src = "";
remote.src = "";
}
function handleNegotiationNeeded() {
pc.createOffer(localDescCreated, logError);
}
function localDescCreated(desc) {
pc.setLocalDescription(desc, function() {
sendMessage(JSON.stringify({'sdp': pc.localDescription}));
}, logError);
}
call.onclick(function(){
createPeerConnection();
});
/////////////////////////////////
function getUserMedia(callback) {
navigator.mediaDevices.getUserMedia({video: true, audio: false}).then(
function(stream) {
callback(stream);
return stream;
}).catch(logError);
}
function displayLocalVideo(stream) {
localStream = stream;
local.src = window.URL.createObjectURL(stream);
local.play();
}
function displayRemoteVideo(stream) {
remoteStream = stream;
remote.src = window.URL.createObjectURL(stream);
remote.play();
}
function logError(error) {
console.log(error);
}
function sendMessage(message) {
socket.emit("message", message);
}
/////// receiving stream //////////
socket.on("message", function(evt){
if(!pc)
createPeerConnection();
var message = JSON.parse(evt.data);
if(message.sdp) {
pc.setRemoteDescription(new RTCSessionDescription(), function() {
if(pc.remoteDescription.type == 'offer')
pc.createAnswer(localDescCreated, logError);
}, logError);
} else {
pc.addIceCandidate(new RTCIceCandidate(message.candidate));
}
});
I think call.onclick() has to work properly for video streaming but it does not also.
You are not seeing your video because you are not using the stream that getUserMedia returns. You need to attach that stream to the video.

Vue Axios form sending empty data instead of image

Alright so I am trying to send image data using JSON but no matter what I do I always end up in sending an empty object... I've tried to console log results but no matter what it just sends empty object
CODE:
<body>
<div id="app">
<div v-if="!image">
<h2>Select an image</h2>
<input type="file" #change="onFileChange" multiple>
</div>
<div v-else>
<div v-for="img in image" class="img_overlay">
<img :src="img" class="img_set"/><br/>
<button #click="removeImage(img)">Remove image</button>
</div>
</div>
</div>
<style>
.img_overlay {
width: 25%;
height: 250px;
float: left;
text-align: center;
}
img {
width: 250px;
height: 200px;
}
</style>
<script type="text/javascript">
new Vue({
el: "#app",
data: {
image: "",
file_data: []
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
else if(files.length == 1)
this.createImage(files)
else if(files.length >= 2)
this.createImage(files)
this.file_data = e.target.files;
this.uploadImage(e.target.files);
},
createImage(file) {
var tmp = [];
for(let i = 0; i < file.length; i++) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {
tmp.push(e.target.result);
};
reader.readAsDataURL(file[i]);
}
vm.image = tmp;
},
removeImage: function (img) {
for(let i = 0; i < this.image.length; i++) {
if(this.image[i] == img) {
this.image.splice(i, 1);
}
}
},
uploadImage: function(x_file) {
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
axios.post('/theme/post_new_image', x_file, config).then(function (response) {
console.log(response);
}).catch(e => { console.log(e); });
}
}
});
</script>
</body>
The result I usualy get is empty object with 5 keys. I've tried to stringify the data and such but I've couldn't find the correct solution for it
You are passing an array of files to your uploadImage function. Try iterating over the array to upload each file:
for (var i = 0, f; f = e.target.files[i]; i++) {
uploadImage(f);
}

Google maps api departureTime in directionsService

I'm trying to set a departureTime options but does not seem to work.
in the example the road ss38 between Bormio and Prato allo Stelvio this season is closed.
Starting in August, I expect that you are using this road and not the one that currently offers through the Swiss.
thanks
Here's my code:
function initialize() {
map = new google.maps.Map(document.getElementById("map"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_CENTER
},
streetViewControl: true,
streetViewControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
}
});
map.setZoom(10); // This will trigger a zoom_changed on the map
map.setCenter(new google.maps.LatLng(46.6199, 10.5924));
directionsDisplay.setMap(map);
geocoderService = new google.maps.Geocoder();
directionsService = new google.maps.DirectionsService;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(46.6199, 10.5924),
map: map,
draggable: true
});
var marker2 = new google.maps.Marker({
position: new google.maps.LatLng(46.4693, 10.3731),
map: map,
draggable: true
});
calcolapercorso(tipodipercorso);
}
function calcolapercorso(tipodipercorso) {
var request = {
origin: new google.maps.LatLng(46.6199, 10.5924),
destination: new google.maps.LatLng(46.4693, 10.3731),
optimizeWaypoints: false,
avoidHighways: true,
region: "IT",
travelMode: google.maps.TravelMode.DRIVING,
drivingOptions: {
departureTime: new Date('2016-08-11T00:00:00'),
trafficModel: google.maps.TrafficModel.PESSIMISTIC
}
};
//request.travelMode = google.maps.DirectionsTravelMode.DRIVING;
request.unitSystem = google.maps.UnitSystem.METRIC;
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var polyLine = {
strokeColor: "#2B8B3F",
strokeOpacity: 1,
strokeWeight: 4,
};
directionsDisplay.setOptions({
polylineOptions: polyLine,
suppressMarkers: true
});
directionsDisplay.setDirections(response);
} else if (status == google.maps.DirectionsStatus.ZERO_RESULTS) {
alert("Could not find a route between these points");
} else {
alert("Directions request failed");
}
});
}
I figured out that the departureTime option does not work when you set any waypoints (at least in Google Maps Javascript API. I didn't confirm RestAPI).
Without waypoints, it worked.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
#map_canvas {
width: 600px;
height: 400px;
border: 1px solid gray;
float: left;
}
#direction_panel {
width: 250px;
height: 400px;
border: 1px solid gray;
overflow-y:scroll;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?language=en&v=3.exp&client=[YOUR_CLIENT_ID]"></script>
<script>
function initialize() {
var mapDiv = document.getElementById("map_canvas");
var map = new google.maps.Map(mapDiv, {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var form = document.getElementById("form");
google.maps.event.addDomListener(form, "submit", function(event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.cancelBubble = true;
event.returnValue = false;
}
map.set("traffic", google.maps.TrafficModel[this.trafficModel.value]);
});
var directionsService = new google.maps.DirectionsService();
map.set("directionsService", directionsService);
var panelDiv = document.getElementById("direction_panel");
var directionsRenderer = new google.maps.DirectionsRenderer({
map: map,
panel: panelDiv
});
map.set("directionsRenderer", directionsRenderer);
map.addListener("traffic_changed", onTrafficModelChanged);
}
function onTrafficModelChanged() {
var map = this;
var departureDateTime = document.getElementById("departureTime").value;
var directionsService = map.get("directionsService");
var directionsRenderer = map.get("directionsRenderer");
var trafficModel = map.get("traffic");
var request = {
origin: "<YOUR ORIGIN>",
destination: "<YOUR DESTINATION>",
travelMode: google.maps.TravelMode.DRIVING,
drivingOptions: {
departureTime: new Date(departureDateTime),
trafficModel: trafficModel
}
};
directionsService.route(request, function(result, status) {
if (status != google.maps.DirectionsStatus.OK) {
alert(status);
return;
}
directionsRenderer.setDirections(result);
});
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
</head>
<body>
<div id="frame">
<div id="map_canvas"></div>
<div id="direction_panel"></div>
</div>
<form id="form">
Departure Time: <input type="text" id="departureTime" size=40 value="2016/01/25 21:00 PST"><br>
<input type="radio" name="trafficModel" value="OPTIMISTIC">Optimistic
<input type="radio" name="trafficModel" value="BEST_GUESS" checked>BEST_GUESS
<input type="radio" name="trafficModel" value="PESSIMISTIC">PESSIMISTIC
<input type="submit" value="Search">
</form>
</body>
</html>

Geocoding Address input Google Maps API

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { width: 1000px; height: 600px } /* ID */
</style>
<!--Include the Maps API JavaScript using a script tag.-->
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
//Function called when the window loads shown below in the addDomlistener
function initialize() {
var geocoder = new google.maps.Geocoder();
var mapOptions = { center: new google.maps.LatLng(40.5, -75.5), zoom: 8 };
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
function calcAddress(address)
{
var address = document.getElementById("address").value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//Got result, center the map and put it out there
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<input id="address" type="text">
<input type="button" value="Search" onclick="calcAddress()" />
</div>
<div id="map-canvas"/>
</body>
</html>
I'm learning about google maps API, and I am just trying to get a simple address search to work, what am I missing? I've seen similar posts, but can't find what isn't right, might need some fresh eyes.
Varaibles map and geocoder are not visible outside of initialize() function. If you open console there is error written:
ReferenceError: geocoder is not defined
They should be made global like:
var map,
geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = { center: new google.maps.LatLng(40.5, -75.5), zoom: 8 };
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
Additionaly, div tag is not self-closing.
<div id="map-canvas"/>
should be changed to
<div id="map-canvas"></div>

Error when running Google Places Autocomplete API

I'm new to the Google Places Autocomplete API, and to development in general but I'm hoping someone can help point me in the right direction. I've reviewed the Google Places documentation and example. In trying to duplicate Google's example in order to gain a better understanding (http://code.google.com/apis/maps/documentation/javascript/examples/places-autocomplete.html), I receive the following error when I run it:
"The Google Maps API server rejected your request. The "sensor" parameter specified in the request must be set to either "true" or "false"."
What's maddening is I do have "sensor" set to "false"! Please see below for the full page code. Any advice would be greatly appreciated.
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"
type="text/javascript"></script>
<style type="text/css">
body {
font-family: sans-serif;
font-size: 14px;
}
#map_canvas {
height: 400px;
width: 600px;
margin-top: 0.6em;
}
</style>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
infowindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
var image = new google.maps.MarkerImage(
place.icon,
new google.maps.Size(71, 71),
new google.maps.Point(0, 0),
new google.maps.Point(17, 34),
new google.maps.Size(35, 35));
marker.setIcon(image);
marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [(place.address_components[0] &&
place.address_components[0].short_name || ''),
(place.address_components[1] &&
place.address_components[1].short_name || ''),
(place.address_components[2] &&
place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function () {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div>
<input id="searchTextField" type="text" size="50">
<input type="radio" name="type" id="changetype-all" checked="checked">
<label for="changetype-all">All</label>
<input type="radio" name="type" id="changetype-establishment">
<label for="changetype-establishment">Establishments</label>
<input type="radio" name="type" id="changetype-geocode">
<label for="changetype-geocode">Geocodes</label>
</div>
<div id="map_canvas"></div>
</body>
</html>
Try this script
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
var image = new google.maps.MarkerImage(
place.icon,
new google.maps.Size(71, 71),
new google.maps.Point(0, 0),
new google.maps.Point(17, 34),
new google.maps.Size(35, 35));
marker.setIcon(image);
marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>