having trouble trying to get a store locator to work in javascript only. i can get the data to load, but when i search for my location with mile radius set, it goes weird, any ideas? the original idea is from a website Click here but obviously it has bugs as it doesn't load my location. This is using google maps v3. Any help would be appreciated
var StoreFinder = (new function(){
// config
var showAllLocationsOnStart = true;
// #PRIVATE variables
var userAddress, markers = [],
image = 'http://cdn1.iconfinder.com/data/icons/fatcow/32x32_0440/flag_red.png',
stores = [
{lat:53.4577, lng:-2.2735, name:'Old Tafford, Manchester'},
{lat:51.4801, lng:-0.18991, name:'Chelsea Football Club'},
{lat:51.5551, lng:-0.1097, name:'Arsenal Football Club'},
{lat:53.4846, lng:-2.2027, name:'Manchester City Football Club'}
];
/* Initialize GMaps ***********************************************/
this.the_map;
this.initialize = function(){
var usCenter = new google.maps.LatLng(52.5813, -1.4446),
myOptions = {zoom:6,center: usCenter,mapTypeId:google.maps.MapTypeId.ROADMAP};
StoreFinder.the_map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
var storeCount = stores.length;
for(i=0; i < storeCount; i++){
var marker = new google.maps.Marker({position: new google.maps.LatLng(stores[i].lat,stores[i].lng),title:stores[i].name,icon: image})
markers.push( marker )
if(showAllLocationsOnStart){ marker.setMap(StoreFinder.the_map); }
}
}
/* End Initialize *************************************************/
// #PRIVATE
function haversineDistance(p1, p2) {
function rad(x) {return x*Math.PI/180;}
var R = 3958.75587;
var dLat = rad( (p2.lat-p1.lat) );
var dLon = rad( (p2.lng-p1.lng) );
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(p1.lat)) * Math.cos(rad(p2.lat)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
// #PRIVATE get distance between two markers (GMARKER OBJECTS)
function getDist(marker1,marker2){
var p1 = { lat:marker1.position.za, lng:marker1.position.Ba },
p2 = { lat:marker2.position.za, lng:marker2.position.Ba };
return haversineDistance(p1, p2);
}
// #PUBLIC clear all markers, then display all store locations
this.showAllLocations = function(){
var storeCount = markers.length;
for(i=0; i < storeCount; i++){
markers[i].setMap(null);
markers[i].setMap(StoreFinder.the_map);
}
var usCenter = new google.maps.LatLng(52.5813, -1.4446);
StoreFinder.the_map.setCenter(usCenter);
StoreFinder.the_map.setZoom(4);
}
// #PUBLIC - geocode person's address (from form inputs), calculate distance to stores,
// then display those within X miles
this.geoCode = function(userLocation,miles){
var geocoder = new google.maps.Geocoder();
var _stores = markers; //#IMPORTANT: markers is the array of instantiated Gmarker objects (don't use the STORES variable)
geocoder.geocode({'address':userLocation},function(results,status){
if(userAddress === null || userAddress === undefined){
userAddress = new google.maps.Marker({
map:StoreFinder.the_map,
position:results[0].geometry.location
})
}else{
userAddress.setMap(null);
userAddress = new google.maps.Marker({
map:StoreFinder.the_map,
position:results[0].geometry.location
})
}
StoreFinder.the_map.setCenter( new google.maps.LatLng(userAddress.position.za, userAddress.position.Ba) );
StoreFinder.the_map.setZoom(5);
var storeCount = _stores.length,
results = 0;
for(i=0; i < storeCount; i++){
_stores[i].setMap(null);
if( getDist(_stores[i],userAddress) < miles ){
_stores[i].setMap(StoreFinder.the_map);
results++;
}
}
var str = results+' store(s) found within '+miles+' miles of your location'
$('#results').empty().append( str );
})
}
})
$(document).ready(function(){
$('#send').click(function(){
var location = $('#address').val(),
miles = $('#sl-miles').val();
if(location.length > 5){ StoreFinder.geoCode(location,miles); }else{ StoreFinder.showAllLocations(); }
})
})
</script>
</head>
<body onload="StoreFinder.initialize()" style="padding:10px;">
<div id="store_locator_sorting">
<label for="address"><span>A</span>
<input id="address" name="address" />
</label>
<label for="sl-miles"><span>Within</span>
<select id="sl-miles" name="sl-miles">
<option value="25">25 Miles</option>
<option value="50">50 Miles</option>
<option value="100">100 Miles</option>
<option value="200">200 Miles</option>
<option value="500">500 Miles</option>
</select>
</label>
<button id="send" type="button" >Find</button> <span style="font-size:11px;text-transform:uppercase;cursor:pointer;">( <a onclick="StoreFinder.showAllLocations();">Reset Map</a> )</span>
</div>
<div id="map_canvas" style="float:left;width:750px;height:530px;border:5px solid #ddd;"></div>
<div id="results" style="float:left;"></div>
Try using the position.lat() and position.lng() methods instead of position.za and position.Ba.
So your getDist function would be:
// #PRIVATE get distance between two markers (GMARKER OBJECTS)
function getDist(marker1,marker2){
var p1 = { lat:marker1.position.lat(), lng:marker1.position.lng() },
p2 = { lat:marker2.position.lat(), lng:marker2.position.lng() };
return haversineDistance(p1, p2);
}
And in your geoCode:
StoreFinder.the_map.setCenter( new google.maps.LatLng(userAddress.position.lat(), userAddress.position.lng()));
Related
I have to select a marker in a map based on the button click. I have multiple marker with each marker associated to button below. I want to change "myloc" on that button click and by default it must select 13, 100.
Html
<div class="row">
<input type="button" id="btn-first" class="btn-a" value = "First">
<input type="button" id="btn-second" class="btn-a" value = "Second">
</div>
JS
let myloc = new L.LatLng(13, 100);
var map = L.map('map').setView(myloc, 12);
$(function () {
$('.btn-a').on('click', function(e){
e.preventDefault();
var clsName = $(this).val();
var lat, long;
if (clsName == 'First') {
lat = 13;
long = 100;
} else if(clasName = 'Second') {
lat = 14;
long = 101;
}
})
});
I dont see you setting the myLoc object anywhere. You are just assigning value for lat, lng. Check the snippet below to see if it answers your question.
Here, you initiliaze myLoc and on button click get new values for lat, lng and set it at the end again for myLoc
//just a temp function to show the example. Dont add this in your code
var L = {
LatLng: function(lat, lng) {
console.log("Current Values for Lat, Lng: " + lat + " , "+ lng);
}
}
let myloc = new L.LatLng(13, 100);
//var map = L.map('map').setView(myloc, 12);
$(function () {
$('.btn-a').on('click', function(e){
// e.preventDefault();
var clsName = $(this).val();
var lat, long;
if (clsName == 'First') {
lat = 13;
long = 100;
} else if(clasName = 'Second') {
lat = 14;
long = 101;
}
//set the myloc here
myloc = new L.LatLng(lat, long);
//then map again
//L.map('map').setView(myloc, 12)
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<input type="button" id="btn-first" class="btn-a" value = "First">
<input type="button" id="btn-second" class="btn-a" value = "Second">
</div>
Below is an approach you can use, similar to what you we're doing. The example uses event delegation to monitor button clicks and then sets the lat and long variables accordingly. Those variables are then used to update the value of the global myLoc. I used an object literal in place of your new L.LatLng object for simplicity.
let myLoc = {
lat: 13,
long: 100
};
//new L.LatLng(13, 100);
document.querySelector('.row').addEventListener('click', function(e) {
if (e.target.type === 'button') {
let lat = 0;
let long = 0;
if (e.target.id === 'btn-first') {
lat = 13;
long = 100;
} else if (e.target.id === 'btn-second') {
lat = 14;
long = 101;
}
myLoc = {
lat,
long
};
console.log(`myLoc.lat: ${myLoc.lat}; myLoc.long ${myLoc.long}`);
//new L.LatLng(lat, long);
}
});
<div class="row">
<input type="button" id="btn-first" class="btn-a" value="First">
<input type="button" id="btn-second" class="btn-a" value="Second">
</div>
$(document).ready(function () {
$('.btn-a').each(function () {
$(this).click(function () {
var $this = $(this).val();
if ($this == 'First') {
$(this).val('One');
} else if ($this == 'Second') {
$(this).val('Two');
}
})
});
});
I am working on a local weather site through freecodecamp. I was wondering if anyone could help me figure out how to assign jQuery to show parenthesis around negative numbers. i.e. when it is -5 degrees I am trying to get it to say (-5).
Here is the jQuery I am currently working with...
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var long;
var lat;
lat = position.coords.latitude;
long = position.coords.longitude;
var api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=79b001616877b59c717616181ee219ec";
$.getJSON(api, function(info) {
var farh;
var cels;
var kelvin;
var tempMin;
var minTemp;
var tempMax;
var maxTemp;
var tempMinC;
var minTempC;
var tempMaxC;
var maxTempC;
var strF = ("\u00B0'F'");
var tempSwitch = false;
kelvin = info.main.temp;
farh = Math.round((kelvin) * (9 / 5) - 459.67);
cels = Math.round(kelvin - 273);
tempMinC = info.main.temp_min;
minTempC = Math.round(tempMinC - 273);
tempMaxC = info.main.temp_max;
maxTempC = Math.round(tempMaxC - 273);
tempMin = info.main.temp_min;
minTemp = Math.round((tempMin) * (9 / 5) - 459.67);
tempMax = info.main.temp_max;
maxTemp = Math.round((tempMax) * (9 / 5) - 459.67);
var city = info.name;
var weatherInfo = info.weather[0].description;
var forecastLow = minTemp;
var forecastHigh = maxTemp;
var forecastLowC = minTempC;
var forecastHighC = maxTempC;
var currCond = info.weather[0].icon;
$('#farh').html(farh);
$('#city').html(city);
$('#weatherInfo').html(weatherInfo);
$('#forecastLow').html(forecastLow);
$('#forecastHigh').html(forecastHigh);
$('#currCond').html(currCond);
$('#switch').click(function() {
if (tempSwitch === false) {
$('#farh').html(cels);
$('#forecastLow').html(forecastLowC)
$('#forecastHigh').html(forecastHighC)
tempSwitch = true;
} else {
$('#farh').html(farh);
$('#forecastLow').html(forecastLow);
$('#forecastHigh').html(forecastHigh);
tempSwitch = false;
}
});
});
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<h2 class="weather-header" id="city"></h2>
<h1><span class="curr-temp" id="farh"></span><span class="curr-temp">°</span></h1>
<div class="col-md-5"></div>
<div class="col-md-2">
<label class="switched">
<input type="checkbox" id="switch">
<div class="slider"></div>
</label>
</div>
<div class="col-md-5"></div>
<h3><span class="hi-lo" id="forecastLow"></span> Low - <span class="hi-lo" id="forecastHigh"></span> High</h3>
<p class="forecast" id="weatherInfo"></p>
You can create a function like this to format your Output:
function formatTemperature(value){
if(value < 0)
return "(" + value + ")";
else
return value;
};
and wrap your values calling this function, passing the values.
I've updated your snippet example.
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var long;
var lat;
lat = position.coords.latitude;
long = position.coords.longitude;
var api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=79b001616877b59c717616181ee219ec";
$.getJSON(api, function(info) {
var farh;
var cels;
var kelvin;
var tempMin;
var minTemp;
var tempMax;
var maxTemp;
var tempMinC;
var minTempC;
var tempMaxC;
var maxTempC;
var strF = ("\u00B0'F'");
var tempSwitch = false;
kelvin = info.main.temp;
farh = Math.round((kelvin) * (9 / 5) - 459.67);
cels = Math.round(kelvin - 273);
tempMinC = info.main.temp_min;
minTempC = Math.round(tempMinC - 273);
tempMaxC = info.main.temp_max;
maxTempC = Math.round(tempMaxC - 273);
tempMin = info.main.temp_min;
minTemp = Math.round((tempMin) * (9 / 5) - 459.67);
tempMax = info.main.temp_max;
maxTemp = Math.round((tempMax) * (9 / 5) - 459.67);
var city = info.name;
var weatherInfo = info.weather[0].description;
var forecastLow = minTemp;
var forecastHigh = maxTemp;
var forecastLowC = minTempC;
var forecastHighC = maxTempC;
var currCond = info.weather[0].icon;
function formatTemperature(value){
if(value < 0)
return "(" + value + ")";
else
return value;
}
$('#farh').html(farh);
$('#city').html(city);
$('#weatherInfo').html(weatherInfo);
$('#forecastLow').html(forecastLow);
$('#forecastHigh').html(forecastHigh);
$('#currCond').html(currCond);
$('#switch').click(function() {
if (tempSwitch === false) {
$('#farh').html(formatTemperature(cels));
$('#forecastLow').html(formatTemperature(forecastLowC));
$('#forecastHigh').html(formatTemperature(forecastHighC));
tempSwitch = true;
} else {
$('#farh').html(formatTemperature(farh));
$('#forecastLow').html(formatTemperature(forecastLow));
$('#forecastHigh').html(formatTemperature(forecastHigh));
tempSwitch = false;
}
});
});
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<h2 class="weather-header" id="city"></h2>
<h1><span class="curr-temp" id="farh"></span><span class="curr-temp">°</span></h1>
<div class="col-md-5"></div>
<div class="col-md-2">
<label class="switched">
<input type="checkbox" id="switch">
<div class="slider"></div>
</label>
</div>
<div class="col-md-5"></div>
<h3><span class="hi-lo" id="forecastLow"></span> Low - <span class="hi-lo" id="forecastHigh"></span> High</h3>
<p class="forecast" id="weatherInfo"></p>
I'm new to google maps api ,i'm trying to draw polygons using google maps api , I want to show the project of the polygon and that project polygon above (inside) allow to draw the building polygon.
I'm trying to clear all my polygon objects before I import new geoJSON data and create new objects.I can't seem to get the setMap(null) function to work correctly. Hopefully someone can kindly let me know where I am failing.
demo
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry,places&sensor=true"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<input type="hidden" id="center_point" value="12.939884,77.62540710000007" />
<input type="hidden" id="projectPolygon" value="" />
<input type="hidden" id="autocompleteLat" value="12.939884" />
<input type="hidden" id="autocompleteLng" value="77.62540710000007" />
<input type="hidden" id="poly_map_codes" value="" />
<input type="hidden" id="zoom_level" value="18" />
<textarea id="xml_valuesMain" style="display:none;">[{"source":"project","latlng":[{"lat":"12.940573081014005","lng":"77.62384235858917"},{"lat":"12.940656731834343","lng":"77.62625098228455"},{"lat":"12.939532671591135","lng":"77.6263153553009"},{"lat":"12.939564040782932","lng":"77.62391209602356"}]}]</textarea>
<textarea id="xml_values" style="display:none;">[{"source":"project","latlng":[{"lat":"12.940573081014005","lng":"77.62384235858917"},{"lat":"12.940656731834343","lng":"77.62625098228455"},{"lat":"12.939532671591135","lng":"77.6263153553009"},{"lat":"12.939564040782932","lng":"77.62391209602356"}]}]</textarea>
<div id="init_map" style="height: 600px;"></div>
<script>
$(function(){
initMap();
});
function initMap()
{
var polygons = [];
var coordinates = [];
var markers=[];
var latt=$('#autocompleteLat').val();
var lngg=$('#autocompleteLng').val();
var amsterdam = new google.maps.LatLng(latt,lngg);
var zoom_level=parseInt($('#zoom_level').val());
var map = new google.maps.Map(document.getElementById('init_map'),{ center: amsterdam, zoom: zoom_level, mapTypeId:google.maps.MapTypeId.SATELLITE });
drawSecondPolygon();
function drawSecondPolygon()
{
google.maps.event.trigger(map, 'refresh');
var data =$('#xml_values').val();
var jsonData = JSON.parse(data);
var polygons = [];
console.log("polygon length="+polygons.length);
for( var i = 0; i < polygons.length; i++ )
{
polygons[i].setMap(null)
}
polygons.length = 0;
for (var i = 0; i < jsonData.length; i++)
{
var latArr = jsonData[i].latlng;
var source_d = jsonData[i].source;
arr = [];
for(j=0; j<latArr.length;j++)
{
var lat=latArr[j].lat;
var lng=latArr[j].lng;
arr.push(new google.maps.LatLng(parseFloat(lat),parseFloat(lng)));
}
if(source_d=="project") { var FillColor='#DA70D6'; var StrokeColr='#BA55D3'; var editval=false; }
else if(source_d=="tower") { var FillColor='#FF8800'; var StrokeColr='#FF8800'; var editval=true; }
else if(source_d=="amenity") { var FillColor='#990000'; var StrokeColr='#990000'; var editval=false; }
else { var FillColor='#66FF00'; var StrokeColr='#66FF00'; var editval=false; }
polygons.push(new google.maps.Polygon({
paths: arr,
Source:source_d,
strokeColor: StrokeColr,
strokeOpacity: 0.8,
strokeWeight: 2,
editable:editval,
clickable:true,
fillColor: FillColor,
fillOpacity: 0.35
}));
console.log("polygons.length="+polygons.length);
polygons[polygons.length-1].setMap(null);
polygons[polygons.length-1].setMap(map);
if(editval==false)
{
console.log("Something working fine");
google.maps.event.addListener(polygons[polygons.length-1], 'click', function (clickEvent)
{
polygons[polygons.length-1].setMap(null);
var newLatLng=$('#poly_map_codes').val();
var clickEventLat=clickEvent.latLng.lat();
var clickEventLng=clickEvent.latLng.lng();
if(newLatLng!='') { newLatLng+=","+clickEventLat+" "+clickEventLng; }
else { newLatLng+=clickEventLat+" "+clickEventLng; }
$('#poly_map_codes').val(newLatLng);
//console.log(newLatLng);
//drawSecondPolygon();
if(newLatLng)
{
var getLatLng=newLatLng;
var getLatLngArr=getLatLng.split(",");
var main_LatLngArr=[];
for(i=0; i<getLatLngArr.length; i++)
{
var my_object={};
var getLatLngExp=getLatLngArr[i].split(" ");
my_object.lat=getLatLngExp[0];
my_object.lng=getLatLngExp[1];
main_LatLngArr.push(my_object);
}
var LatLngObj={};
LatLngObj.source="tower";
LatLngObj.latlng=main_LatLngArr;
var oldPolyArr=$('#xml_valuesMain').val();
var oldPolyArr=JSON.parse(oldPolyArr);
oldPolyArr.push(LatLngObj);
$('#xml_values').val(JSON.stringify(oldPolyArr));
polygons[polygons.length-1].setMap(null);
drawSecondPolygon();
console.log("oldPolyArr="+JSON.stringify(oldPolyArr));
}
});
}
}
}
}
</script>
At a first look you redeclare the var polygons = []; in your drawSecondPolygon function this override the content of the same variable declared in initMap ..
thi comment this line .. so you can use always the parent polygons array
function drawSecondPolygon()
{
google.maps.event.trigger(map, 'refresh');
var data =$('#xml_values').val();
var jsonData = JSON.parse(data);
//var polygons = [];
Here is the code I have so far. Someone posted it for people to use. It calculates distance well but when I try to calculate my delivery cost, it wont give me an error but it also won't output the value. The "$?" stays the same. I don't have a lot of experience coding and I've tried a number of things. I'm at a loss here. Please help!
<font face="cookie"><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script>
<!-- Browser key 1 -->
<script src="http://maps.google.com/maps? file=api&v=2&key=AIzaSyA9kMASRkOAbPFdzd4u5o_F0JyXKieOSQk" type="text/javascript"></script>
<script type="text/javascript">
//Initialize location vars
var location1;
var location2;
$(document).ready(function() {
console.log('test');
initialize();
//Grab the address values from the form on submit, and then run the maps code
$('#map-form').submit(function(event) {
//Also, stop the form from actually submitting
event.preventDefault();
address1 = $('#address1').val();
address2 = $('#address2').val();
//Run it, baby!
showLocation();
});
});
var geocoder, location1, location2;
function initialize() {
//Create new object of the google maps api
geocoder = new GClientGeocoder();
}
function showLocation() {
geocoder.getLocations(address1, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode address 1");
}
else
{
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
geocoder.getLocations(address2, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode address 2");
}
else
{
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
calculateDistance();
}
});
}
});
}
function calculateDistance()
{
try
{
var glatlng1 = new GLatLng(location1.lat, location1.lon);
var glatlng2 = new GLatLng(location2.lat, location2.lon);
var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
var kmdistance = (miledistance * 1.609344).toFixed(1);
//Write the value wherever you want!
$('#mile_distance').html(miledistance);
}
catch (error)
{
alert(error);
}
}
price = $('#price').val();
delivery = $('#delivery').val();
var miles = mile_distance - 25;
if (miles<0)
{
miles = 0;
}
var C = (miles * .575);
$('#price').val(C.toFixed(2));
var delivery_cost = 10;
var D = (delivery_cost + price);
$('#delivery').val(D.toFixed(2));
</script>
<form id="map-form">
<input type="text" placeholder="Address 1" id="address1" />
<input type="text" placeholder="Address 2" id="address2" />
<input type="submit" value="Submit" />
</form>
<p>The distance is: <span id="mile_distance">?</span> miles</p>
<p>Your delivery cost is: $<span id="delivery">?</span> </p>
</font>
The following code is not a part of any function and, therefore, will be executed immediately after it's loaded, even before your GUI fully appears on the screen.
price = $('#price').val();
delivery = $('#delivery').val();
var miles = mile_distance - 25;
if (miles < 0) {
miles = 0;
}
var C = (miles * .575);
$('#price').val(C.toFixed(2));
var delivery_cost = 10;
var D = (delivery_cost + price);
$('#delivery').val(D.toFixed(2));
I'm stuck on this and it's so simple but I don't understand anything of JavaScript.
Basically I want to create a simple calculation to know the travel time, based on three different variables. I'm Dutch so some words are Dutch and some are English in the code. The first variable is the "woonplaats" which is the starting location. The second one is the "bestemming" which is the location of destination. The third one is the "vervoer" which is the vehicle you'll travel by.
Now all of these variables have a standard value. So the only thing that needs to be done is the calculation.
This is what my script code looks like:
function location() {
var woonplaats = document.getElementById("woonplaats").value;
switch (woonplaats) {
case "amstelveen":
locationAm();
break;
case "badhoevedorp":
poelBa();
break;
div2.innerHTML = "Jouw gemiddelde reistijd is: <b>" + tijd + "</b> km/h";
function locationAm() {
var e = document.getElementById("bestemming");
var eindbest = e.options[e.selectedIndex].value;
var x = document.getElementById("bestemming");
var vervoer = x.options[e.selectedIndex].value;
if (eindbest == ameer) {
var distance = 14500 ; }
else if (eindbest === groning) {
var distance = 183000 ; }
else if(eindbest === zwolle) {
var distance = 114000 ;
}
if (vervoer === kuruma ) {
var time = distance / 28 ;
}
else if (vervoer === jitensha) {
var time = var distance / 4 ;
}
else if ( vervoer === densha) {
var time = var distance / 56 ;
}
else if (vervoer === scoot) {
var time = var distance / 8 ; }
div2.innerHTML = "your travel time will be <b>" + time + "</b> km/h";
}
function locationBa() {
var e = document.getElementById("bestemming");
var eindbest = e.options[e.selectedIndex].value;
var x = document.getElementById("bestemming");
var vervoer = x.options[e.selectedIndex].value;
if (eindbest == ameer) {
var distance = 13000 ; }
else if (eindbest === groning) {
var distance = 40000 ; }
else if(eindbest === zwolle) {
var distance = 600000 ;
}
if (vervoer === kuruma ) {
var time = distance / 28 ;
}
else if (vervoer === jitensha) {
var time = var distance / 4 ;
}
else if ( vervoer === densha) {
var time = var distance / 56 ;
}
else if (vervoer === scoot) {
var time = var distance / 8 ; }
div2.innerHTML = "your travel time will be: <b>" + time + "</b>";
And this is my body
<form>
I live in <select id="woonplaats">
<option value="amstelveen">Amstelveen</option>
<option value="badhoevedorp">Badhoevedorp</option>
</select>
<p></p>
I'll travel to <select id="bestemming">
<option value="ameer">Aalsmeer</option>
<option value="groning">Groningen</option>
<option value="zwol">Zwolle</option>
</select>
<p></p>
My vehicle is <select id="vervoer">
<option value="kuruma">Auto</option>
<option value="jitensha">Fiets</option>
<option value="scoot">Scooter</option>
<option value="densha">Trein</option>
</select>
<p></p>
<p></p>
calculate time <input onclick="poel()" type="button" value="Bereken!">
</form>
<p> </p>
<div id="div2">your travel time will be.. gemiddelde ... km/h</div>
Basically the idea is that the first and the second variable decide the distance between them, and the vehicle decides at which speed you'll travel, so it should calculate the travel time.
That's an immense amount of code for a relatively simple problem.
You should encode the distances as data tables instead of logic, and put the vehicle speeds directly into the form as the value attribute of the individual option elements:
The code below does the whole thing:
var distances = {
amstelveen: {
ameer: 14500,
groning: 183000,
einbest: 11400
},
badhoevedorp: {
ameer: 13000,
groning: 40000,
zwolle: 600000
}
};
document.getElementById('calculate').addEventListener('click', function () {
var from = document.getElementById('woonplaats').value;
var to = document.getElementById('bestemming').value;
var speed = +document.getElementById('vervoer').value;
var distance = distances[from][to];
var time = distance / speed;
document.getElementById('div2').innerHTML = "your travel time will be: <b>" + time + "</b>";
}, false);
Demo at http://jsfiddle.net/alnitak/cwdhbk2x/