TheThreeNewbies | When Landslides Strike

Athens

Team Updates

When Landslides Strike
Project Scope
The project we took over aims at populating the global LandSlide database with observations made by individuals. This will help people get information real time about several places on Earth where landslides have occurred and, thus, protect themselves from accidents. Moreover, this Web Application should be user friendly, giving the ability to the user to insert his personal observations to the system. Finally, according to the records in the database, the application should give clues to the user about places that are dangerous for future possible landslide and inform him accordingly.
Project Design & Resources
In this project, we were concerned mainly to build a web app which would be very easy and user friendly for an individual to handle. The user must be able to obtain, insert and view data in short time. Also, the data the user inserts must be valid, or else the database will be filled with corrupted and wrong data, something that would affect extremely the purpose of the application. Several validation mechanism were implemented for this reason.
Besides, the user must be able to view locations on Earth, where already landslides have occurred. With the selection of a particular country around the world, the user is able to view on a Map all the locations together, with locations that landslides may occur in the long run.
The project was built on Java and Google Map APIs. More specifically, for the Front-End part we used JavaScript, HTML, CSS2, Google Map APIs & JSF, whereas for the Back-End we used Spring. For Database support, we used MySQL and ORM technologies such as JPA and Hibernate.
Project Implementation
When the App launches, the user is navigated to the page (img_1.jpg) where he can insert his own observations.
There is a welcome logo at the top of the page and an infinite banner with a friendly message. On the right side, there is a Google Map with a red marker in order to navigate to the exact location he observed a landslide.
On the left side, there is a short description of the purpose of this site and direction on what the user should do, in order to insert a valid observation to the system. Below, there is a form with specific fields to fill, there is a small panel that shows real time what is the Address & Country the user has currently selected on the Map and also, two buttons: Save button to insert his observation and View Records to see all available landslides on Earth, at every country. The latter button will turn to a new page for this operation.
According to user operations, several messages appear on screen indicating if he performed a valid operation or not. In this case, where the user submits correctly his data, a success message with green color appears on screen (img_2.jpg).
In order to maintain the validity and accuracy of the data, we prompt the user to Save data only if he zoomed to the Map above 75%.
After saving his observation, the user is able to view the landslide records. After pressing View Records button, he is navigated to another page with relevant information (img_3.jpg).
On the right side, there is the Google Map where the user will have a visual representation of the landslide locations, previewed as clusters (when zoom is small, several points that exists within specific area create a cluster) and as individual points on Map, when zoom is greater.
When Landslides Strike
Project Scope
The project we took over aims at populating the global LandSlide database with observations made by individuals. This will help people get information real time about several places on Earth where landslides have occurred and, thus, protect themselves from accidents. Moreover, this Web Application should be user friendly, giving the ability to the user to insert his personal observations to the system. Finally, according to the records in the database, the application should give clues to the user about places that are dangerous for future possible landslide and inform him accordingly.
Project Design & Resources
In this project, we were concerned mainly to build a web app which would be very easy and user friendly for an individual to handle. The user must be able to obtain, insert and view data in short time. Also, the data the user inserts must be valid, or else the database will be filled with corrupted and wrong data, something that would affect extremely the purpose of the application. Several validation mechanism were implemented for this reason.
Besides, the user must be able to view locations on Earth, where already landslides have occurred. With the selection of a particular country around the world, the user is able to view on a Map all the locations together, with locations that landslides may occur in the long run.
The project was built on Java and Google Map APIs. More specifically, for the Front-End part we used JavaScript, HTML, CSS2, Google Map APIs & JSF, whereas for the Back-End we used Spring. For Database support, we used MySQL and ORM technologies such as JPA and Hibernate.
Project Implementation
When the App launches, the user is navigated to the page where he can insert his own observations.
There is a welcome logo at the top of the page and an infinite banner with a friendly message. On the right side, there is a Google Map with a red marker in order to navigate to the exact location he observed a landslide.
On the left side, there is a short description of the purpose of this site and direction on what the user should do, in order to insert a valid observation to the system. Below, there is a form with specific fields to fill, there is a small panel that shows real time what is the Address & Country the user has currently selected on the Map and also, two buttons: Save button to insert his observation and View Records to see all available landslides on Earth, at every country. The latter button will turn to a new page for this operation.
According to user operations, several messages appear on screen indicating if he performed a valid operation or not. In this case, where the user submits correctly his data, a success message with green color appears on screen.
In order to maintain the validity and accuracy of the data, we prompt the user to Save data only if he zoomed to the Map above 75%.
After saving his observation, the user is able to view the landslide records. After pressing View Records button, he is navigated to another page with relevant information.
On the right side, there is the Google Map where the user will have a visual representation of the landslide locations, previewed as clusters (when zoom is small, several points that exists within specific area create a cluster) and as individual points on Map, when zoom is greater.
On the left side, there lay the components that define the actual functionality. There are messages with clear instructions on the steps need to be taken. At first, there is a drop-down list that prompts the user to select the country for which he wishes to look on the data. When the country is selected, the users clicks the Calculate Data button. This spawns an operation to the back end, where the landslide observations for that specific country are collected. Finally, the user clicks on the Show Results button and the locations on the Map reveal (img_4.jpg).
With blue color are clusters that contain observations (the number on the cluster reveals how many locations there are). The flags are actual locations that landslides have occurred.
Project Operations Flow
On the client side, we have two pages: index.xhtml, which is the initial page, and reports.xhtml. Both of them include a Google Map (included with Google Map API & JavaScript) to locate a specific point.
In index.xhtml is that we want to capture the longitude, latitude & country we locate the Map Marker. Besides, the user fills a form with relevant information (landslide size, type, what triggered the landslide, how many people were injured, e.t.c). Then, by invoking its associated bean on server side (GeoBean.java), after performing some basic validations aiming to check he validity of the record to be inserted, we insert the record to the database. This is done by passing the information through several application layers. The classes LandSlideManager.java, LandSlideDAO.java & LandSlide.java fulfill this purpose and the ORM we have used to map database entities to Java classes and persist the records to database (Hibernate, JPA).
The same principles apply also to reports.xhtml. A basic form that submits fields to the database through calling methods from its backing bean (ReportBean.java) and passing it through the same classes as mentioned above.
Project Considerations
Although the app is functional, there are some things that need to be considered, as also things that we didn’t manage (due to lack of resources: very small team, time limit) to address:
 No clustering algorithm eventually was implemented (k-means) to “predict” from the dataset locations that landslides may occur. Currently, we only project the observations that have already been committed to database
 We didn’t verify the weather conditions for the current observations (is it raining at that particular time? Is the ground still wet?)
 Validate the locations are reasonable. As an example, it is not a valid record a point on Map that is located to the sea!
 Does the user enters a location where actually a landslide occurred? This could be cross-validated with real-time data from another database, maybe from a satelite
greeksupersayaDimitris Anagnostopoulos
This is the project Structure. If anyone wants to run the project, knows how.
This is the project Structure. If anyone wants to run the project, knows how.
greeksupersayaDimitris Anagnostopoulos
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.spaceappslandslides.bean;
/**
*
* @author Dimitris
*/
import com.spaceappslandslides.manager.LandslideManager;
import com.spaceappslandslides.persistence.LandslideData;
import javax.inject.Named;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
*
* @author Dimitris
*/
@Named
@Component
@Scope("session")
public class ReportBean implements Serializable{
private String country;
private String arrayOfStrings;
private ArrayList<String> landslideDB;
private ArrayList<LandslideData> landslideCountryData;
private ArrayList<CountryObject> countriesDB;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public ArrayList<CountryObject> getCountriesDB() {
return countriesDB;
}
public void setCountriesDB(ArrayList<CountryObject> countriesDB) {
this.countriesDB = countriesDB;
}
public ArrayList<String> getLandslideDB() {
return landslideDB;
}
public void setLandslideDB(ArrayList<String> landslideDB) {
this.landslideDB = landslideDB;
}
public ArrayList<LandslideData> getLandslideCountryData() {
return landslideCountryData;
}
public void setLandslideCountryData(ArrayList<LandslideData> landslideCountryData) {
this.landslideCountryData = landslideCountryData;
}
public String getArrayOfStrings() {
return arrayOfStrings;
}
public void setArrayOfStrings(String arrayOfStrings) {
this.arrayOfStrings = arrayOfStrings;
}
// Inject DAO Manager
@Inject
LandslideManager landslideManager;
public void setLandslideManager(LandslideManager landslideManager) {
this.landslideManager = landslideManager;
}
public void initializeBean(){
if (!FacesContext.getCurrentInstance().isPostback() || !FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest()) {
try{
countriesDB = new ArrayList<>();
landslideCountryData = new ArrayList<>();
countriesDB.add(new CountryObject("None","None"));
landslideDB = this.landslideManager.findUniqueCountries();
if(!landslideDB.isEmpty()){
countriesDB.clear();
for(String ld : landslideDB){
countriesDB.add(new CountryObject(ld,ld));
}
}
}
catch(Exception ex){
System.out.println("Exception in ReportBean initializeBean(): "+ex.getMessage());
}
}
}
public String calculateData(){
System.out.println("Country: "+country);
arrayOfStrings = "";
landslideCountryData = this.landslideManager.findLandslideDataByCountry(country);
if(!landslideCountryData.isEmpty()){
for(LandslideData ld : landslideCountryData){
arrayOfStrings+=(ld.getLatitude()+":::"+ld.getLongitude()+"@");
}
}
System.out.println("Array Of Strings: "+arrayOfStrings);
return null;
}
///////////////////////// Wrapper object ////////////////////////////////////
public class CountryObject{
public String countryLabel;
public String countryValue;
public CountryObject(String countryLabel, String countryValue){
this.countryLabel = countryLabel;
this.countryValue = countryValue;
}
public String getYearLabel(){
return countryLabel;
}
public String getYearValue(){
return countryValue;
}
}
}
view raw ReportBean.java hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:flow="http://www.springframework.org/schema/webflow-config"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:osgi="http://www.springframework.org/schema/osgi"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.3.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.3.xsd
http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi-1.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd
">
<context:component-scan base-package="com.spaceappslandslides" />
<context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spaceapps" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="ds"/>
<property name="annotatedClasses">
<list>
<value>com.spaceappslandslides.persistence.LandslideData</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
view raw spring-hibernate.xml hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:jsf="http://xmlns.jcp.org/jsf">
<h:head>
<title>Landslide</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script async='async' defer='defer' src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBM2vtkxr1DIEU4uRqEByKFcc9JLbLsJ-s" type="text/javascript"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<f:event listener="#{reportBean.initializeBean}" type="preRenderView" />
<style>
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</h:head>
<h:body style="background-color: lightgrey;">
<h2 style="position:absolute;left:500px;color: dimgray;">Welcome to the LandSlides world!</h2>
<div id="theBanner" style="position:relative;top:60px;left:1000px;width:430px;height:20px;opacity:1;font-size:18px;color: dimgray;">Have you ever observed a landslide?</div>
<br></br>
<div id="map" style="position:absolute;top:100px;left:550px;width:800px;height:500px;"></div>
<h:outputText style="position:absolute;top:100px;left:10px;width:500px;font-size:18px;color:dimgray;" value="Below you can find instructions on how to visualize the LandSlides all over the world."/>
<br></br>
<h:form id="theForm" style="position:relative;top:50px;width:600px;">
<h:panelGrid columns="2" id="panelGrid">
<h:outputLabel for="countryList" style="color: dimgray;font-weight:bold;" value="1. Select the country you wish to see LandSlides (required)"/>
<h:selectOneListbox id="countryList" style="position:relative;top:120px;left:-185px;width:190px;border-radius:20px;padding:5px;border:dimgray 2px solid;" value="#{reportBean.country}" size="10">
<f:selectItems value="#{reportBean.countriesDB}" var="y" itemLabel="#{y.yearLabel}" itemValue="#{y.yearValue}" />
</h:selectOneListbox>
</h:panelGrid>
<h:outputText style="position:absolute;top:320px;left:10px;color:dimgray;font-weight:bold;" value="2. Press the Calculate Data button to calculate the LandSlides"/>
<h:commandButton style="position:absolute;top:350px;left:10px;" value="Calculate Data" action="#{reportBean.calculateData()}">
</h:commandButton>
<h:outputText style="position:absolute;top:400px;left:10px;color:dimgray;font-weight:bold;" value="3. Press the Show results button for preview on the Map"/>
<h:commandButton style="position:absolute;top:430px;left:10px;" onclick="createClusters()" value="Show results">
<f:ajax event="click" render="map" execute="@this"/>
</h:commandButton>
<div id="arrayOfStrings" style="visibility:hidden;">#{reportBean.arrayOfStrings}</div>
</h:form>
<script>
var mapCanvas;
var myCenter;
var mapOptions;
var map;
var marker;
var zoomNow;
window.onload = function() {initMap();bannerAnim();};
function initMap() {
console.log('We are in!');
mapCanvas = document.getElementById("map");
myCenter = new google.maps.LatLng(-28.024,140.887);
mapOptions = {center: myCenter, zoom: 3};
map = new google.maps.Map(mapCanvas,mapOptions);
zoomNow = map.getZoom();
marker = new google.maps.Marker({
position: myCenter,
map:map,
draggable:true
});
// ZoomIn - ZoomOut //
google.maps.event.addListener(map,'zoom_changed',function(){
zoomNow = map.getZoom();
});
}
////////////// New Stuff //////////////////
///////////////////////////////////////////
function createClusters(){
//<![CDATA[
mapCanvas = document.getElementById("map");
myCenter = new google.maps.LatLng(marker.getPosition().lat(),marker.getPosition().lng());
mapOptions = {center: myCenter, zoom: zoomNow};
map = new google.maps.Map(mapCanvas,mapOptions);
// Create an array of alphabetical characters used to label the markers.
var arrayOfStrings = document.getElementById('arrayOfStrings');
var locations = [];
if(arrayOfStrings!==null || arrayOfStrings!== 'undefined'){
var res = arrayOfStrings.innerHTML.split('@');
console.log('arrayOfStrings: '+arrayOfStrings.innerHTML);
for(var i = 0; i < res.length; i++){
console.log('res: '+res[i]);
var newRes = res[i].split(':::');
console.log('Lat: '+newRes[0]+' - Lng: '+newRes[1]);
locations.push({'lat':parseFloat(newRes[0]), 'lng': parseFloat(newRes[1])});
}
}
for(var i = 0; i < locations.length; i++){
console.log(i+'th location: '+locations[i]);
}
//var locations = [
// {'lat': -31.563910, 'lng': 147.154312},
// {'lat': -33.718234, 'lng': 150.363181},
// {'lat': -33.727111, 'lng': 150.371124},
// {'lat': -33.848588, 'lng': 151.209834},
// {'lat': -33.851702, 'lng': 151.216968},
// {'lat': -34.671264, 'lng': 150.863657},
// {'lat': -35.304724, 'lng': 148.662905},
// {'lat': -36.817685, 'lng': 175.699196},
// {'lat': -36.828611, 'lng': 175.790222},
// {'lat': -37.750000, 'lng': 145.116667},
// {'lat': -37.759859, 'lng': 145.128708},
// {'lat': -37.765015, 'lng': 145.133858},
// {'lat': -37.770104, 'lng': 145.143299},
// {'lat': -37.773700, 'lng': 145.145187},
// {'lat': -37.774785, 'lng': 145.137978},
// {'lat': -37.819616, 'lng': 144.968119},
// {'lat': -38.330766, 'lng': 144.695692},
// {'lat': -39.927193, 'lng': 175.053218},
// {'lat': -41.330162, 'lng': 174.865694},
// {'lat': -42.734358, 'lng': 147.439506},
// {'lat': -42.734358, 'lng': 147.501315},
// {'lat': -42.735258, 'lng': 147.438000},
// {'lat': -43.999792, 'lng': 170.463352}
// ];
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
icon:image
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
//]]>
}
//////////// Banner Animation ////////////////
function bannerAnim() {
//<![CDATA[
var elem = document.getElementById('theBanner');
var pos = 1000;
var opac = 0;
elem.style.opacity = opac;
var id = setInterval(frame, 15);
function frame() {
if (pos === -400) {
clearInterval(id);
bannerAnim();
} else {
pos--;
elem.style.left = pos + 'px';
if(pos<1000){
opac+=0.01;
elem.style.opacity = opac;
}
}
}
//]]>
}
</script>
</h:body>
</html>
view raw reports.xhtml hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.spaceappslandslides.manager;
/**
*
* @author Dimitris
*/
import com.spaceappslandslides.dao.LandslideDAO;
import com.spaceappslandslides.persistence.LandslideData;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class LandslideManager {
@Inject
public LandslideDAO landslideDAO;
public void setLandslideDAO(LandslideDAO landslideDAO) {
this.landslideDAO = landslideDAO;
}
public ArrayList<String> findUniqueCountries(){
return this.landslideDAO.findUniqueCountries();
}
public ArrayList<LandslideData> findLandslideDataByCountry(String country){
return this.landslideDAO.findLandslideDataByCountry(country);
}
public void submitLandslideData(String currentDate,String country,String hazardType,String lanslideType,String trigger,int fatal,int injured,String lanslideSize,String photo,String lat,String lon,String geoLoc){
this.landslideDAO.submitLandslideData(currentDate, country, hazardType, lanslideType, trigger, fatal, injured, lanslideSize, photo, lat, lon, geoLoc);
}
}
greeksupersayaDimitris Anagnostopoulos
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.spaceappslandslides.dao;
import com.spaceappslandslides.persistence.LandslideData;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.inject.Named;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
@Named
@Transactional("transactionManager")
public class LandslideDAO {
@Inject
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public ArrayList<String> findUniqueCountries(){
Session session = this.sessionFactory.getCurrentSession();
ArrayList<String> landslideData = new ArrayList<>();
try{
landslideData = (ArrayList<String>)session.getNamedQuery("LandslideData.findUniqueCountries").list();
}catch (Throwable ex) {
System.err.println("Exception in findLandslideDataByCountry(): " + ex.getMessage());
throw new ExceptionInInitializerError(ex);
}
return landslideData;
}
public ArrayList<LandslideData> findLandslideDataByCountry(String country){
Session session = this.sessionFactory.getCurrentSession();
ArrayList<LandslideData> landslideData = new ArrayList<>();
try{
landslideData = (ArrayList<LandslideData>)session.getNamedQuery("LandslideData.findByCountry").setParameter("country", country).list();
}catch (Throwable ex) {
System.err.println("Exception in findLandslideDataByCountry(): " + ex.getMessage());
throw new ExceptionInInitializerError(ex);
}
return landslideData;
}
public void submitLandslideData(String currentDate,String country,String hazardType,String lanslideType,String trigger,int fatal,int injured,String lanslideSize,String photo,String lat,String lon,String geoLoc){
try{
Session session = this.sessionFactory.getCurrentSession();
LandslideData observationToInsert = new LandslideData();
observationToInsert.setDatesubmitted(currentDate);
observationToInsert.setCountry(country);
observationToInsert.setHazardtype(hazardType);
observationToInsert.setLandslidetype(lanslideType);
observationToInsert.setTriggerType(trigger);
observationToInsert.setFatalities(fatal);
observationToInsert.setInjuries(injured);
observationToInsert.setLandslidesize(lanslideSize);
observationToInsert.setPhotolink(photo);
observationToInsert.setLatitude(lat);
observationToInsert.setLongitude(lon);
observationToInsert.setGeolocation(geoLoc);
session.persist(observationToInsert);
}
catch(Exception ex){
System.out.println("Exception in submitLandslideData(): "+ex.getMessage());
}
}
}
view raw LandslideDAO.java hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.spaceappslandslides.persistence;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name = "landslidedata")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "LandslideData.findAll", query = "SELECT l FROM LandslideData l"),
@NamedQuery(name = "LandslideData.findUniqueCountries", query = "SELECT DISTINCT l.country FROM LandslideData l ORDER BY l.country ASC"),
@NamedQuery(name = "LandslideData.findByDate", query = "SELECT l FROM LandslideData l WHERE l.datesubmitted=:datesubmitted"),
@NamedQuery(name = "LandslideData.findByCountry", query = "SELECT l FROM LandslideData l WHERE l.country=:country")
})
public class LandslideData implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer ID;
@Size(max = 255)
@Column(name = "datesubmitted")
private String datesubmitted;
@Size(max = 255)
@Column(name = "country")
private String country;
@Size(max = 45)
@Column(name = "hazardtype")
private String hazardtype;
@Size(max = 255)
@Column(name = "landslidetype")
private String landslidetype;
@Size(max = 255)
@Column(name = "triggerType")
private String triggerType;
@Basic(optional = false)
@Column(name = "fatalities")
private Integer fatalities;
@Basic(optional = false)
@Column(name = "injuries")
private Integer injuries;
@Size(max = 255)
@Column(name = "landslidesize")
private String landslidesize;
@Column(name = "photolink", length = 65535)
private String photolink;
@Size(max = 255)
@Column(name = "latitude")
private String latitude;
@Size(max = 255)
@Column(name = "longitude")
private String longitude;
@Size(max = 255)
@Column(name = "geolocation")
private String geolocation;
public LandslideData() {}
public LandslideData(Integer ID, String datesubmitted, String country, String hazardtype, String landslidetype, String triggerType, Integer fatalities, Integer injuries, String landslidesize, String photolink, String latitude, String longitude, String geolocation) {
this.ID = ID;
this.datesubmitted = datesubmitted;
this.country = country;
this.hazardtype = hazardtype;
this.landslidetype = landslidetype;
this.triggerType = triggerType;
this.fatalities = fatalities;
this.injuries = injuries;
this.landslidesize = landslidesize;
this.photolink = photolink;
this.latitude = latitude;
this.longitude = longitude;
this.geolocation = geolocation;
}
public Integer getID() {
return ID;
}
public void setID(Integer ID) {
this.ID = ID;
}
public String getDatesubmitted() {
return datesubmitted;
}
public void setDatesubmitted(String datesubmitted) {
this.datesubmitted = datesubmitted;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHazardtype() {
return hazardtype;
}
public void setHazardtype(String hazardtype) {
this.hazardtype = hazardtype;
}
public String getLandslidetype() {
return landslidetype;
}
public void setLandslidetype(String landslidetype) {
this.landslidetype = landslidetype;
}
public String getTriggerType() {
return triggerType;
}
public void setTriggerType(String triggerType) {
this.triggerType = triggerType;
}
public Integer getFatalities() {
return fatalities;
}
public void setFatalities(Integer fatalities) {
this.fatalities = fatalities;
}
public Integer getInjuries() {
return injuries;
}
public void setInjuries(Integer injuries) {
this.injuries = injuries;
}
public String getLandslidesize() {
return landslidesize;
}
public void setLandslidesize(String landslidesize) {
this.landslidesize = landslidesize;
}
public String getPhotolink() {
return photolink;
}
public void setPhotolink(String photolink) {
this.photolink = photolink;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getGeolocation() {
return geolocation;
}
public void setGeolocation(String geolocation) {
this.geolocation = geolocation;
}
@Override
public int hashCode() {
int hash = 3;
hash = 97 * hash + Objects.hashCode(this.ID);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final LandslideData other = (LandslideData) obj;
if (!Objects.equals(this.ID, other.ID)) {
return false;
}
return true;
}
@Override
public String toString() {
return "LandslideData{" + "ID=" + ID + ", datesubmitted=" + datesubmitted + ", country=" + country + ", hazardtype=" + hazardtype + ", landslidetype=" + landslidetype + ", triggerType=" + triggerType + ", fatalities=" + fatalities + ", injuries=" + injuries + ", landslidesize=" + landslidesize + ", photolink=" + photolink + ", latitude=" + latitude + ", longitude=" + longitude + ", geolocation=" + geolocation + '}';
}
}
view raw LandslideData.java hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.spaceappslandslides.manager;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Named
@Component
@Scope("session")
public class SessionManager implements Serializable{
public void onIdle() {
try {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().clear();
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
context.redirect("/SpaceAppsLandSlides/index.xhtml");
} catch (IOException ex) {
Logger.getLogger(SessionManager.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Exception handled: "+ex.getMessage());
}
}
public void toSuccess() {
try {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().clear();
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
context.redirect("/SpaceAppsLandSlides/reports.xhtml");
} catch (IOException ex) {
Logger.getLogger(SessionManager.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Exception handled: "+ex.getMessage());
}
}
}
view raw SessionManager.java hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>
</faces-config>
view raw faces-config.xml hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/errorPages/notFound.xhtml</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/errorPages/error.xhtml</location>
</error-page>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<!--///////////////////////////// END of FACES ////////////////////////////////////-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-hibernate.xml
</param-value>
</context-param>
<!--///////////////////////////// END of SPRING ////////////////////////////////////-->
</web-app>
view raw web.xml hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.SpaceAppsLandSlides</groupId>
<artifactId>SpaceAppsLandSlides</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpaceAppsLandSlides</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.13</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.13</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.7.Final</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.5.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.4</version>
</dependency>
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-websocket-core</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-client</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
view raw pom.xml hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.spaceappslandslides.bean;
import com.spaceappslandslides.manager.LandslideManager;
import javax.inject.Named;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
*
* @author Dimitris
*/
@Named
@Component
@Scope("session")
public class GeoBean implements Serializable{
private String lanslideType;
private String trigger;
private String lanslideSize;
private String errorMsg;
private String errorStyle;
private String fatal;
private String injured;
public String getLanslideType() {
return lanslideType;
}
public void setLanslideType(String lanslideType) {
this.lanslideType = lanslideType;
}
public String getTrigger() {
return trigger;
}
public void setTrigger(String trigger) {
this.trigger = trigger;
}
public String getFatal() {
return fatal;
}
public void setFatal(String fatal) {
this.fatal = fatal;
}
public String getInjured() {
return injured;
}
public void setInjured(String injured) {
this.injured = injured;
}
public String getLanslideSize() {
return lanslideSize;
}
public void setLanslideSize(String lanslideSize) {
this.lanslideSize = lanslideSize;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getErrorStyle() {
return errorStyle;
}
public void setErrorStyle(String errorStyle) {
this.errorStyle = errorStyle;
}
// Inject DAO Manager
@Inject
LandslideManager landslideManager;
public void setLandslideManager(LandslideManager landslideManager) {
this.landslideManager = landslideManager;
}
public void initializeData() {
if (!FacesContext.getCurrentInstance().isPostback() || !FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest()) {
try{
lanslideType = "";
trigger = "";
lanslideSize = "";
errorMsg = "";
errorStyle = "position:relative;top:170px;font-weight: bold; font-size: 16px; color: darkred;";
fatal = "";
injured = "";
System.out.println("In constructor");
System.out.println("lanslideType: "+lanslideType);
System.out.println("trigger: "+trigger);
System.out.println("lanslideSize: "+lanslideSize);
}
catch(Exception ex){
System.out.println("Exception in GeoBean initializeData(): "+ex.getMessage());
}
}
}
public void errorMethod(){
try{
errorMsg = "";
if((lanslideType==null || lanslideType.length()==0) || (trigger==null || trigger.length()==0) || (lanslideSize==null || lanslideSize.length()==0)){
System.out.println("Its IN errorMethod!");
errorMsg = "Be careful! You can not leave any of the first 3 questions unanswered";
}
else{
if(!StringUtils.isNumeric(fatal) || !StringUtils.isNumeric(injured)){
errorMsg = "Be careful! Optional fields must be numeric";
}
}
}
catch(Exception ex){
System.out.println("Exception in GeoBean errorMethod(): "+ex.getMessage());
}
}
public String saveData(){
try{
// System.out.println("lanslideType: "+lanslideType);
// System.out.println("trigger: "+trigger);
// System.out.println("lanslideSize: "+lanslideSize);
// System.out.println("fatal: "+fatal);
// System.out.println("injured: "+injured);
errorMsg = "";
if((lanslideType==null || lanslideType.length()==0) || (trigger==null || trigger.length()==0) || (lanslideSize==null || lanslideSize.length()==0) || !StringUtils.isNumeric(fatal) || !StringUtils.isNumeric(injured)){
System.out.println("Error IN displayData!");
errorMsg = "You have unsaved data";
return null;
}
//String textAreaMsg = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("messageToBean");
//System.out.println("INFO from Client: "+textAreaMsg);
errorMsg = "Your data are saved to the global Database!";
errorStyle = "position:relative;top:170px;font-weight: bold; font-size: 16px; color: ForestGreen;";
String[] receivedData = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("messageToBean").split(":::");
/////// Now that everything is ok, you may save the data to DB!!! //////
// Id is autoincrement
// First Column
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String currentDate = sdf.format(new Date());
// Second column
String country = receivedData[0].trim();
// Third column
String hazardType = "Landslide";
// Fourth column got it already - lanslideType
// Fifth column got it already - trigger
// Sixth column - convert fatal to integer
Double d1 = Double.parseDouble(fatal);
int intFatal = d1.intValue();
// Seventh column - convert fatal to integer
Double d2 = Double.parseDouble(injured);
int intInjured = d2.intValue();
// Eigth column got it already - lanslideSize
// Ninth column not yet - later to be used to upload photos in base64 format
String photo = "";
// Tenth column
String lat = receivedData[1].trim();
// Eighteenth column
String lon = receivedData[2].trim();
// Twelveth column
String geoLocation = "("+lat+","+lon+")";
// Save the Data
this.landslideManager.submitLandslideData(currentDate, country, hazardType, lanslideType, trigger, intFatal, intInjured, lanslideSize, photo, lat, lon, geoLocation);
////////////////////////////////////////////////////////////////////////
}
catch(Exception ex){
System.out.println("Exception in GeoBean saveData(): "+ex.getMessage());
}
return null;
}
}
view raw GeoBean.java hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<title>Polyglot</title>
<h:body style="background-color: lightgrey;">
<h:panelGrid columns="1">
<h2 style="color: slategray;">We can't find the page you are asking for</h2>
<h:form>
<h4 style="color: slategray;">You are prompted to return to <h:commandLink style="color: buttonshadow;" action="#{sessionManager.onIdle()}">initial</h:commandLink> page</h4>
</h:form>
</h:panelGrid>
</h:body>
</html>
view raw notFound.xhtml hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<title>Polyglot</title>
<h:body style="background-color: lightgrey;">
<h:panelGrid columns="1">
<h2 style="color: slategray;">There is a internal server Error when proceeding with your request</h2>
<h:form>
<h4 style="color: slategray;">You are prompted to return to <h:commandLink style="color: buttonshadow;" action="#{sessionManager.onIdle()}">initial</h:commandLink> page</h4>
</h:form>
</h:panelGrid>
</h:body>
</html>
view raw error.xhtml hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Landslide</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script async='async' defer='defer' src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBM2vtkxr1DIEU4uRqEByKFcc9JLbLsJ-s" type="text/javascript"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
<!--
To use this code on your website, get a free API key from Google.
Read more at: https://www.w3schools.com/graphics/google_maps_basic.asp
-->
<f:event listener="#{geoBean.initializeData()}" type="preRenderView" />
</h:head>
<h:body style="background-color: lightgrey;">
<h2 style="position:absolute;left:500px;color: dimgray;">Welcome to the LandSlides world!</h2>
<div id="theBanner" style="position:relative;top:60px;left:1000px;width:430px;height:20px;opacity:1;font-size:18px;color: dimgray;">Have you ever observed a landslide?</div>
<br></br>
<div id="map-canvas" style="position:absolute;top:100px;left:550px;width:800px;height:500px;"></div>
<h:outputText style="position:absolute;top:100px;left:10px;width:500px;font-size:18px;color: dimgray;" value="In this page, you can share your personal experience with the rest of the world.
You are prompted to locate the exact point of LandSlide in the map with the use of the marker. Fill in the other fields
of the form and submit. Your observation, is commited among others to the global database of LandSlide occurences.
You may save someone's life! In any case, you can make the world safer!
"/>
<br></br>
<h:form id="errorForm">
<h:outputText id="errorText" style="#{geoBean.errorStyle}" value="#{geoBean.errorMsg}"/>
</h:form>
<h:form id="landSlideForm" style="position:relative;top:180px;width:550px;">
<h:panelGrid columns="2" id="panelGrid">
<h:outputLabel for="landslideType" style="color: dimgray;font-weight:bold;" value="1. What kind of LandSlide you observed? (required)"/>
<h:selectOneListbox id="landslideType" style="position:relative;top:-7px;left:-35px;width:190px;border-radius:20px;padding:5px;border:dimgray 2px solid;" value="#{geoBean.lanslideType}" size="3">
<f:selectItem itemValue="Complex" itemLabel="Complex" />
<f:selectItem itemValue="Creep" itemLabel="Creep" />
<f:selectItem itemValue="Debris_Flow" itemLabel="Debris Flow" />
<f:selectItem itemValue="Lahar" itemLabel="Lahar" />
<f:selectItem itemValue="Landslide" itemLabel="Landslide" />
<f:selectItem itemValue="Mudslide" itemLabel="Mudslide" />
<f:selectItem itemValue="Other" itemLabel="Other" />
<f:selectItem itemValue="Rockfall" itemLabel="Rockfall" />
<f:selectItem itemValue="Snow_Avalanche" itemLabel="Snow Avalanche" />
<f:selectItem itemValue="Unknown" itemLabel="Unknown" />
</h:selectOneListbox>
<h:outputLabel for="trigger" style="color: dimgray;font-weight:bold;" value="2. What triggered the LandSlide? (required)"/>
<h:selectOneListbox id="trigger" style="position:relative;top:7px;left:-35px;width:190px;border-radius:20px;padding:5px;border:dimgray 2px solid;" value="#{geoBean.trigger}" size="3">
<f:selectItem itemValue="Construction" itemLabel="Construction" />
<f:selectItem itemValue="Continuous_rain" itemLabel="Continuous rain" />
<f:selectItem itemValue="Dam_Embankment_Collapse" itemLabel="Dam Embankment Collapse" />
<f:selectItem itemValue="Downpour" itemLabel="Downpour" />
<f:selectItem itemValue="Flooding" itemLabel="Flooding" />
<f:selectItem itemValue="Freeze_thaw" itemLabel="Freeze thaw" />
<f:selectItem itemValue="Mining_digging" itemLabel="Mining digging" />
<f:selectItem itemValue="No_apparent_trigger" itemLabel="No apparent trigger" />
<f:selectItem itemValue="Other" itemLabel="Other" />
<f:selectItem itemValue="Rain" itemLabel="Rain" />
<f:selectItem itemValue="Snowfall_snowmelt" itemLabel="Snowfall snowmelt" />
<f:selectItem itemValue="Tropical_Cyclone" itemLabel="Tropical Cyclone" />
<f:selectItem itemValue="Unknown" itemLabel="Unknown" />
</h:selectOneListbox>
<h:outputLabel for="landslideSize" style="color: dimgray;font-weight:bold;" value="3. What is the LandSlide size? (required)"/>
<h:selectOneListbox id="landslideSize" style="position:relative;top:15px;left:-35px;width:190px;border-radius:20px;padding:5px;border:dimgray 2px solid;" value="#{geoBean.lanslideSize}" size="3">
<f:selectItem itemValue="Large" itemLabel="Large" />
<f:selectItem itemValue="Medium" itemLabel="Medium" />
<f:selectItem itemValue="Small" itemLabel="Small" />
<f:selectItem itemValue="Unknown" itemLabel="Unknown" />
<f:selectItem itemValue="Very_large" itemLabel="Very large" />
</h:selectOneListbox>
<h:outputLabel for="fatals" style="position:relative;top:15px;color: dimgray;font-weight:bold;" value="4. How many people died? (optional)"/>
<h:inputText id="fatals" style="position:relative;top:15px;left:-35px;width:190px;border-radius:20px;padding:5px;border:dimgray 2px solid;" value="#{geoBean.fatal}"/>
<h:outputLabel for="injured" style="position:relative;top:15px;color: dimgray;font-weight:bold;" value="5. How many people injured? (optional)"/>
<h:inputText id="injured" style="position:relative;top:15px;left:-35px;width:190px;border-radius:20px;padding:5px;border:dimgray 2px solid;" value="#{geoBean.injured}"/>
</h:panelGrid>
<br></br>
<h:commandButton value="Save" onclick="saveButton()" style="border-radius:20px;">
<f:ajax event="click" execute="landSlideForm" render="errorForm:errorText" listener="#{geoBean.errorMethod()}"/>
</h:commandButton>
<h:commandButton value="View Reports" action="#{sessionManager.toSuccess()}" style="border-radius:20px;"/>
<div style="position:relative;top:-10px;left:320px;width:400px;">
<span style="font-size:15px;color: dimgray;font-weight:bold;">Your current selection:</span>
<br></br>
<div style="color:dimgray;">Address: <span id="address"></span></div>
<div style="color:dimgray;">Country: <span id="country"></span></div>
<div style="color:dimgray;visibility:hidden;">Latitude: <span id="latitude"></span></div>
<div style="color:dimgray;visibility:hidden;">Longitude: <span id="longitude"></span></div>
<div style="visibility:hidden;">Zoom: <span id="zoom"></span></div>
</div>
</h:form>
<h:form id="backingBeanForm">
<input type="hidden" id="msgToBean" name="messageToBean" value="Test"/>
<h:commandLink id="link" value="click" style="visibility:hidden;">
<f:ajax event="click" execute="@this" listener="#{geoBean.saveData}" render="errorForm:errorText"/>
</h:commandLink>
</h:form>
<script>
window.onload = function() {initMap();bannerAnim();};
function initMap() {
console.log('We are in!');
var mapCanvas = document.getElementById("map-canvas");
var myCenter = new google.maps.LatLng(37.970184106981336,23.74145468749998);
var mapOptions = {center: myCenter, zoom: 5};
var map = new google.maps.Map(mapCanvas,mapOptions);
var marker = new google.maps.Marker({
position: myCenter,
map:map,
draggable:true
});
// Initialize variables
var lat = document.getElementById('latitude');
var lng = document.getElementById('longitude');
var zoomThreshold = document.getElementById('zoom');
console.log('Zoom Init: '+map.getZoom());
lat.innerHTML = marker.getPosition().lat();
lng.innerHTML = marker.getPosition().lng();
zoomThreshold.innerHTML = map.getZoom();
// Drag the Marker //
google.maps.event.addListener(marker,'dragend',function(){
console.log('Latitude: '+marker.getPosition().lat()+' - Longitude: '+marker.getPosition().lng());
var lat = document.getElementById('latitude');
var lng = document.getElementById('longitude');
var zoomThreshold = document.getElementById('zoom');
console.log('Zoom: '+map.getZoom());
lat.innerHTML = marker.getPosition().lat();
lng.innerHTML = marker.getPosition().lng();
zoomThreshold.innerHTML = map.getZoom();
});
// ZoomIn - ZoomOut //
google.maps.event.addListener(map,'zoom_changed',function(){
console.log('Zoom: '+map.getZoom());
var zoomThreshold = document.getElementById('zoom');
zoomThreshold.innerHTML = map.getZoom();
});
}
function saveButton(){
//<![CDATA[
var zoomThreshold = document.getElementById('zoom');
if(zoomThreshold.innerHTML<15){
console.log('Too low...');
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
var lat = document.getElementById('latitude').innerHTML;
var lng = document.getElementById('longitude').innerHTML;
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + '%2C' + lng + '&language=en';
//var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
//var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=39.03625238705127%2C22.20336874999998&language=en';
$.getJSON(GEOCODING).done(function(location) {
var stringArray = location.results[0].formatted_address.split(',');
if(isNaN(stringArray[stringArray.length-1].trim().replace(/\s/g,''))===true){
$('#country').html(stringArray[stringArray.length-1]);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(lat);
$('#longitude').html(lng);
}
else if(isNaN(stringArray[stringArray.length-1].trim().replace(/\s/g,''))===false){
$('#country').html(stringArray[stringArray.length-2]);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(lat);
$('#longitude').html(lng);
}
});
}
function error(err) {
console.log(err);
}
alert('Your location is not aqurate.\nYour current zoom is '+(zoomThreshold.innerHTML*5)+'%\nYou need to zoom at least 75%');
}
if(zoomThreshold.innerHTML>=15){
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
var lat = document.getElementById('latitude').innerHTML;
var lng = document.getElementById('longitude').innerHTML;
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + '%2C' + lng + '&language=en';
//var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
//var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=39.03625238705127%2C22.20336874999998&language=en';
$.getJSON(GEOCODING).done(function(location) {
var stringArray = location.results[0].formatted_address.split(',');
if(isNaN(stringArray[stringArray.length-1].trim().replace(/\s/g,''))===true){
console.log('Not a number!: '+stringArray[stringArray.length-1]);
$('#country').html(stringArray[stringArray.length-1]);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(lat);
$('#longitude').html(lng);
// Send them to BackEnd
invokeCommandLink(stringArray[stringArray.length-1],lat,lng);
}
else if(isNaN(stringArray[stringArray.length-1].trim().replace(/\s/g,''))===false){
console.log('Is a number!: '+stringArray[stringArray.length-1]);
console.log('Thus, the country is: '+stringArray[stringArray.length-2]);
$('#country').html(stringArray[stringArray.length-2]);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(lat);
$('#longitude').html(lng);
// Send them to BackEnd
invokeCommandLink(stringArray[stringArray.length-2],lat,lng);
}
//var errorElement = document.getElementById('errorForm:errorText');
//errorElement.innerHTML = 'Your data are saved to the global Database!';
//errorElement.style = 'position:relative;top:210px;font-weight: bold; font-size: 16px; color: ForestGreen;';
});
}
function error(err) {
console.log(err);
}
}
//]]>
}
//////////// Send information to Backing Bean ////////////////
function invokeCommandLink(country,lat,lng) {
var jsfCommandLink = document.getElementById('backingBeanForm:link');
var hiddenField = document.getElementById('msgToBean');
hiddenField.value = country+':::'+lat+':::'+lng;
jsfCommandLink.click();
}
//////////// Banner Animation ////////////////
function bannerAnim() {
//<![CDATA[
var elem = document.getElementById('theBanner');
var pos = 1000;
var opac = 0;
elem.style.opacity = opac;
var id = setInterval(frame, 15);
function frame() {
if (pos === -400) {
clearInterval(id);
bannerAnim();
} else {
pos--;
elem.style.left = pos + 'px';
if(pos<1000){
opac+=0.01;
elem.style.opacity = opac;
}
}
}
//]]>
}
</script>
</h:body>
</html>
view raw index.xhtml hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBM2vtkxr1DIEU4uRqEByKFcc9JLbLsJ-s&callback=initMap" type="text/javascript"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
<!--
To use this code on your website, get a free API key from Google.
Read more at: https://www.w3schools.com/graphics/google_maps_basic.asp
-->
</head>
<body>
<div id="map-canvas" style="position:absolute;top:10px;left:500px;width:800px;height:500px;"></div>
<br><br>
<div>Country: <span id="country"></span>
<div>State: <span id="state"></span>
<div>City: <span id="city"></span>
<div>Latitude: <span id="latitude"></span>
<div>Longitude: <span id="longitude"></span>
<div>Address: <span id="address"></span>
<div>Zoom: <span id="zoom"></span>
<br><br>
<button type="button" id="btn">Save!</button>
<script>
function initMap() {
var mapCanvas = document.getElementById("map-canvas");
var myCenter = new google.maps.LatLng(37.970184106981336,23.74145468749998);
var mapOptions = {center: myCenter, zoom: 10};
var map = new google.maps.Map(mapCanvas,mapOptions);
var marker = new google.maps.Marker({
position: myCenter,
map:map,
draggable:true
});
// Drag the Marker //
google.maps.event.addListener(marker,'dragend',function(){
console.log('Latitude: '+marker.getPosition().lat()+' - Longitude: '+marker.getPosition().lng());
var lat = document.getElementById('latitude');
var lng = document.getElementById('longitude');
var zoomThreshold = document.getElementById('zoom');
console.log('Zoom: '+map.getZoom());
lat.innerHTML = marker.getPosition().lat();
lng.innerHTML = marker.getPosition().lng();
zoomThreshold.innerHTML = map.getZoom();
});
// ZoomIn - ZoomOut //
google.maps.event.addListener(map,'zoom_changed',function(){
console.log('Zoom: '+map.getZoom());
var zoomThreshold = document.getElementById('zoom');
zoomThreshold.innerHTML = map.getZoom();
});
}
$("#btn").click(function(){
var zoomThreshold = document.getElementById('zoom');
if(zoomThreshold.innerHTML<15){
console.log('Too low...');
}
if(zoomThreshold.innerHTML<=15){
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
var lat = document.getElementById('latitude').innerHTML;
var lng = document.getElementById('longitude').innerHTML;
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + '%2C' + lng + '&language=en';
//var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
//var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=39.03625238705127%2C22.20336874999998&language=en';
$.getJSON(GEOCODING).done(function(location) {
var stringArray = location.results[0].formatted_address.split(',');
if(isNaN(stringArray[stringArray.length-1].trim().replace(/\s/g,''))===true){
console.log('Not a number!: '+stringArray[stringArray.length-1]);
$('#country').html(stringArray[stringArray.length-1]);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(lat);
$('#longitude').html(lng);
}
else if(isNaN(stringArray[stringArray.length-1].trim().replace(/\s/g,''))===false){
console.log('Is a number!: '+stringArray[stringArray.length-2]);
$('#country').html(stringArray[stringArray.length-2]);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(lat);
$('#longitude').html(lng);
}
})
}
function error(err) {
console.log(err)
}
}
});
</script>
</body>
</html>
view raw GoogleMapsLocation hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos

<html>

<head>

<meta charset="UTF-8">

<title></title>

<!--

To use this code on your website, get a free API key from Google.

Read more at: https://www.w3schools.com/graphics/google_maps_bas...

-->

</head>

<body>

<div id="map-canvas" style="position:absolute;top:10px;left:500px;width:800px;height:500px;"></div>

<br><br>

<div>Country: <span id="country"></span></div>

<div>Latitude: <span id="latitude"></span></div>

<div>Longitude: <span id="longitude"></span></div>

<div>Address:<span id="address"</span></div>

<div>Zoom: <span id="zoom"></span></div>

<br><br>

<button type="button" id="btn">Save!</button>

<script>

function initMap() {

var mapCanvas = document.getElementById("map-canvas");

var myCenter = new google.maps.LatLng(37.970184106981336,23.74145468749998);

var mapOptions = {center: myCenter, zoom: 10};

var map = new google.maps.Map(mapCanvas,mapOptions);

var marker = new google.maps.Marker({

position: myCenter,

map:map,

draggable:true

});

// Drag the Marker //

google.maps.event.addListener(marker,'dragend',function(){

console.log('Latitude: '+marker.getPosition().lat()+' - Longitude: '+marker.getPosition().lng());

var lat = document.getElementById('latitude');

var lng = document.getElementById('longitude');

var zoomThreshold = document.getElementById('zoom');

console.log('Zoom: '+map.getZoom());

lat.innerHTML = marker.getPosition().lat();

lng.innerHTML = marker.getPosition().lng();

zoomThreshold.innerHTML = map.getZoom();

});

// ZoomIn - ZoomOut //

google.maps.event.addListener(map,'zoom_changed',function(){

console.log('Zoom: '+map.getZoom());

var zoomThreshold = document.getElementById('zoom');

zoomThreshold.innerHTML = map.getZoom();

});

}

$("#btn").click(function(){

var zoomThreshold = document.getElementById('zoom');

if(zoomThreshold.innerHTML<15){

console.log('Too low...');

}

if(zoomThreshold.innerHTML>=15){

navigator.geolocation.getCurrentPosition(success, error);

function success(position) {

var lat = document.getElementById('latitude').innerHTML;

var lng = document.getElementById('longitude').innerHTML;

var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + '%2C' + lng + '&language=en';

//var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

//var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=39.03625238705127%2C22.20336874999998&language=en';

$.getJSON(GEOCODING).done(function(location) {

var stringArray = location.results[0].formatted_address.split(',');

if(isNaN(stringArray[stringArray.length-1].trim().replace(/\s/g,''))===true){

console.log('Not a number!: '+stringArray[stringArray.length-1]);

$('#country').html(stringArray[stringArray.length-1]);

$('#address').html(location.results[0].formatted_address);

$('#latitude').html(lat);

$('#longitude').html(lng);

}

else if(isNaN(stringArray[stringArray.length-1].trim().replace(/\s/g,''))===false){

console.log('Is a number!: '+stringArray[stringArray.length-2]);

$('#country').html(stringArray[stringArray.length-2]);

$('#address').html(location.results[0].formatted_address);

$('#latitude').html(lat);

$('#longitude').html(lng);

}

})

}

function error(err) {

console.log(err)

}

}

});

</script>

</body>

</html>

adeveloperAnna Dzadzamia
Team Stream Item
giakaramikaramitros ioannis
Team Stream Item
giakaramikaramitros ioannis
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBM2vtkxr1DIEU4uRqEByKFcc9JLbLsJ-s&callback=initMap" type="text/javascript"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
<!--
To use this code on your website, get a free API key from Google.
Read more at: https://www.w3schools.com/graphics/google_maps_basic.asp
-->
</head>
<body>
<div id="map-canvas" style="position:absolute;top:10px;left:500px;width:800px;height:500px;"></div>
<br><br>
<div>Country: <span id="country"></span>
<div>State: <span id="state"></span>
<div>City: <span id="city"></span>
<div>Latitude: <span id="latitude"></span>
<div>Longitude: <span id="longitude"></span>
<div>Address: <span id="address"></span>
<div>Zoom: <span id="zoom"></span>
<br><br>
<button type="button" id="btn">Save!</button>
<script>
function initMap() {
var mapCanvas = document.getElementById("map-canvas");
var myCenter = new google.maps.LatLng(37.970184106981336,23.74145468749998);
var mapOptions = {center: myCenter, zoom: 10};
var map = new google.maps.Map(mapCanvas,mapOptions);
var marker = new google.maps.Marker({
position: myCenter,
map:map,
draggable:true
});
// Drag the Marker //
google.maps.event.addListener(marker,'dragend',function(){
console.log('Latitude: '+marker.getPosition().lat()+' - Longitude: '+marker.getPosition().lng());
var lat = document.getElementById('latitude');
var lng = document.getElementById('longitude');
var zoomThreshold = document.getElementById('zoom');
console.log('Zoom: '+map.getZoom());
lat.innerHTML = marker.getPosition().lat();
lng.innerHTML = marker.getPosition().lng();
zoomThreshold.innerHTML = map.getZoom();
});
// ZoomIn - ZoomOut //
google.maps.event.addListener(map,'zoom_changed',function(){
console.log('Zoom: '+map.getZoom());
var zoomThreshold = document.getElementById('zoom');
zoomThreshold.innerHTML = map.getZoom();
});
}
$("#btn").click(function(){
var zoomThreshold = document.getElementById('zoom');
if(zoomThreshold.innerHTML<15){
console.log('Too low...');
}
if(zoomThreshold.innerHTML<=15){
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
var lat = document.getElementById('latitude').innerHTML;
var lng = document.getElementById('longitude').innerHTML;
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + '%2C' + lng + '&language=en';
//var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
//var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=39.03625238705127%2C22.20336874999998&language=en';
$.getJSON(GEOCODING).done(function(location) {
var stringArray = location.results[0].formatted_address.split(',');
if(isNaN(stringArray[stringArray.length-1].trim().replace(/\s/g,''))===true){
console.log('Not a number!: '+stringArray[stringArray.length-1]);
$('#country').html(stringArray[stringArray.length-1]);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(lat);
$('#longitude').html(lng);
}
else if(isNaN(stringArray[stringArray.length-1].trim().replace(/\s/g,''))===false){
console.log('Is a number!: '+stringArray[stringArray.length-2]);
$('#country').html(stringArray[stringArray.length-2]);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(lat);
$('#longitude').html(lng);
}
})
}
function error(err) {
console.log(err)
}
}
});
</script>
</body>
</html>
view raw GoogleMapsLocation hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBM2vtkxr1DIEU4uRqEByKFcc9JLbLsJ-s&callback=initMap" type="text/javascript"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
<!--
To use this code on your website, get a free API key from Google.
Read more at: https://www.w3schools.com/graphics/google_maps_basic.asp
-->
</head>
<body>
<div id="map-canvas" style="position:absolute;top:10px;left:500px;width:800px;height:500px;"></div>
<br><br>
<div>Country: <span id="country"></span>
<div>State: <span id="state"></span>
<div>City: <span id="city"></span>
<div>Latitude: <span id="latitude"></span>
<div>Longitude: <span id="longitude"></span>
<div>Address: <span id="address"></span>
<div>Zoom: <span id="zoom"></span>
<br><br>
<button type="button" id="btn">Save!</button>
<script>
function initMap() {
var mapCanvas = document.getElementById("map-canvas");
var myCenter = new google.maps.LatLng(37.970184106981336,23.74145468749998);
var mapOptions = {center: myCenter, zoom: 10};
var map = new google.maps.Map(mapCanvas,mapOptions);
var marker = new google.maps.Marker({
position: myCenter,
map:map,
draggable:true
});
// Drag the Marker //
google.maps.event.addListener(marker,'dragend',function(){
console.log('Latitude: '+marker.getPosition().lat()+' - Longitude: '+marker.getPosition().lng());
var lat = document.getElementById('latitude');
var lng = document.getElementById('longitude');
var zoomThreshold = document.getElementById('zoom');
console.log('Zoom: '+map.getZoom());
lat.innerHTML = marker.getPosition().lat();
lng.innerHTML = marker.getPosition().lng();
zoomThreshold.innerHTML = map.getZoom();
});
// ZoomIn - ZoomOut //
google.maps.event.addListener(map,'zoom_changed',function(){
console.log('Zoom: '+map.getZoom());
var zoomThreshold = document.getElementById('zoom');
zoomThreshold.innerHTML = map.getZoom();
});
}
$("#btn").click(function(){
var zoomThreshold = document.getElementById('zoom');
if(zoomThreshold.innerHTML<15){
console.log('Too low...');
}
if(zoomThreshold.innerHTML<=15){
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
var lat = document.getElementById('latitude').innerHTML;
var lng = document.getElementById('longitude').innerHTML;
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + '%2C' + lng + '&language=en';
//var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
//var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=39.03625238705127%2C22.20336874999998&language=en';
$.getJSON(GEOCODING).done(function(location) {
var addressComponentsSize = location.results[0].address_components.length;
$('#country').html(location.results[0].address_components[addressComponentsSize-2].long_name);
$('#state').html(location.results[0].address_components[addressComponentsSize-1].long_name);
//$('#city').html(location.results[0].address_components[2].long_name);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(lat);
$('#longitude').html(lng);
console.log(location.results[0]);
})
}
function error(err) {
console.log(err)
}
}
});
</script>
</body>
</html>
view raw Geolocation hosted with ❤ by GitHub
greeksupersayaDimitris Anagnostopoulos
Team Stream Item
giakaramikaramitros ioannis
NASA Logo

SpaceApps is a NASA incubator innovation program.