Mashup

Goals

One of the advantages of JavaScript is being able to incorporate modules developed by others into your own program in order to develop large-scale software that looks good. Today we will learn to use some of the services provided by others in our own programs.

  • Understand the concept of a mashup
  • Understand the mechanism of using services prepared by others.
  • Learn how to use web services like Google Maps, along with JSON and XML

Web Services

One of the reasons many universities prefer to teach JavaScript as a language is, that it is possible to utilize the services that people all over the world provide via the Web. A library is also one of these servoces, but the Web service is higher than the library in terms of processing on the server side and using data prepared on the server side. This time, we will explain mashups using Web service. Mashups are created to form new services by combining technology and contents from different providers. It is a technology that has attracted attention, and enables you to create large software systems in a very short time. In mashup, you do not need to know program details of the material service, you only need to pay attention to the procedure to call and the format of the data to be sent back, so it is better to create more complex services and data that you do not own you can realize the service you used.

The concept of Web services

As we have learned so far, JavaScript is mainly a language that operates on the browser. Therefore, if you can load JavaScript programs into your browser, you can run the program immediately. In other words, if you can load a function created by another person into the browser, you can use it freely. In the case of a mashup, the loaded program provides various services via the interface provided on the web server.

Webサービスの概念
Webサービスの概念

Using Web services

There are some necessary precautions to be taken while using Web services. Let us look at these in detail.

Programming

To use a Web service is just as simple as to access another site. For this reason, if you use a web service in an infinite loop, you will access a lot of other people’s sites at high speed. Even though the person who wrote the program does not have malicious intent, such an act seems to be a DoS attack (Denial of Service attack) from the viewpoint of the web service provider. When using Web services, please try to create programs with extreme caution so as not to disturb the side that provides Web services.

Security

When embedding other web services on your web page, you need to thoroughly examine their quality. If you embed the malicious web service of another person, you will be responsible for the wrong and may become an accomplice.

For example, if you easily use Web services created by unknown developers, there is a possibility that malicious actions such as leakage of personal information by the Web service may occur even if the service is convenient.

In order to avoid such situations, it is good to choose a web service that is safe enough that many people have used it for a long time.

Terms of Use

When using the Web service, it is necessary to check “terms of use” and adhere to it. For example, there are many cases where it is required to clearly indicate a provider, or to display a specific icon. In recent years, many services require user registration.

For example, it is necessary to pay particular attention,  when copying and using a part of the source of a friend’s home page. It may be necessary to copy not only the service call part but also the credit part, and since the URL will change, it may be necessary to register the user again. It is important to check the usage conditions on the home page of the target Web service provider.

XML and JSON

Many Web services can acquire data in XML format or JSON format. We will explain XML and JSON here.

XML

XML is Extensible Markup Language, it is a Markup Language like HTML. Like the HTML, it is being formulated by the World Wide Web Consortium (W3C). As its name implies, XML can extend elements by defining tags, so it is sometimes called a meta language. Basically, “<tag name>” indicates the beginning of the element, and “</ tag name>” indicates the end of the element. Currently, many formats such as XHTML and KML are developed based on XML.

JSON

XML has been made flexible, and a lot of data has been specified in this format. On the other hand, however, there are also many criticisms that file size becomes large and readability is bad. Therefore, a data description method called JSON (JavaScript Object Notation) that has good affinity with JavaScript was developed.

JSON is a data description method based on an object literal in JavaScript and is specified in RFC 4627. Basically, it follows the JavaScript object literal, but there are restrictions that the numerical value must be decimal notation. Also, the key of the object is supposed to be surrounded by “” in the character string. An example of data expressed in JSON is shown below. In this example, a line break is added for easy viewing, but it is not necessarily required.

{
    "name": {
        "familyName": "Keio",
        "firstName": "Taro"
    },
    "age": 19,
    "gender": "male"
}

Using Web Services: Google Maps

We will learn how to use Google Maps as an example of using Web service here.

Web Services

Complex Web services are provided in the world that we can freely use. When a function in a program created by the user calls another function (called an application program interface, API, etc.) provided by the web service, it communicates with the necessary server and provides a mechanism for using the service.

Webサービス実現の仕組み
Webサービス実現の仕組み

Let’s use a Web service that actually provides content.

Getting started with Google Maps

Below is a pasted version of Google Maps API provided by Google which you see often. Actually this program can be used easily.

The program demonstrated above is as follows. It may seem somewhat confusing compared to previous programs, but if you try it out yourself it is actually not that difficult.

HTML

&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;div id="map" style="width:300px;height:300px"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/div&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;callback=initMap" type="text/javascript"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;script type="text/javascript" src="mymap.js"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

JavaScript

function initMap() {
  // 地図の中心を決める
  var latlng = new google.maps.LatLng(35.388276, 139.427348);

  // 地図を表示するためのオプションを設定する
  var opt = {
    zoom: 15,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  // 地図を表示する。
  var map = new google.maps.Map(document.getElementById('map'), opt);
}

First, the first line of the HTML part secures an area for displaying the map using the div tag. Here, two attributes of id and style are specified, the ID is set to “map” by the id attribute, the size of the area is set to 300 px (pixel) in width and 300 px (pixel) in height by the style attribute .

The third line is reading the API for Google Maps. The Google Maps API  can be found at https://maps.googleapis.com/maps/api/js. So we need to load this program to use the Google Maps API. This line may be in the HTML header. In this case,  the API_KEY must be originally set. API_KEY can be obtained from Google ‘s key acquisition and authentication page. Currently, since the previous API did not require API_KEY, it seems to work without setting API_KEY in order to allow backward compatibility. In order to omit the API_KEY, delete the whole part related to API_KEY from : <script async defer src=”https://maps.googleapis.com/masps/api/api/js?key=YOUR_API_KEY&callback=initMap” type=”text/javascript”></script> so that it now looks like : “<script async defer src =” https://maps.googleapis.com/maps/api/js?callback=initMap “type =” text / javascript “> < / script> “.

Also, Google Maps API v3 has several options. Please see the Google Maps JavaScript API V3 Reference page for details.

The fourth line of the HTML part is a part that reads mymap.js which is a program file to be written by the user. Since we specified initMap () as a callback function when loading the Google Maps API, this program needs to include the initMap () function.

Let’s see the JavaScript program. First, in the third line, the center point of the map to be displayed is determined. We are making a new object with google.maps.LatLng (), but do not care too much about the details, we are just specifying the latitude and longitude as an argument and storing the result in a variable called latlng.

From the sixth line to the tenth line, parameters for actually displaying the map are set. Zoom is specified as 15 indicating the scale of the map. Likewise, the center indicates the center of the map is latlng, which is the variable generated earlie. The mapTypeId indicates the type of the map that is set in the road map (google.maps.MapTypeId.ROADMAP). These are all stored in the variable opt. Please note that opt ​​is an object.

The thirteenth line is finally for displaying the map. We use document.getElementById (‘map’) to specify where to display the map on the Web page, and display the map using the parameters set in opt.

For more detailed usage of the Google Maps API, please see the page and tutorial on the Google Maps JavaScript API V3 Reference, as above.

Setting up event listeners (callback functions) for Google Maps

When you display a map, you want to make some action when you can operate on the map. In order to realize this, Google Maps has the function for setting event listeners. An event listener is a callback function that is called when an event occurs.

See the next program. This shows an event listener added to the function for displaying the above map. On line 21, the event listener is set so that the click_callback () function is called for the click event. Also, the click_callback () function starting at line 16 is the body of the event listener. click_callback () has one dummy argument, and the state at the time of event occurrence is set in this variable. In this program, on the 17th line, latitude and longitude of the place where the event occurred, that is, the place where the event was clicked is displayed using alert ().

See the Google Maps JavaScript API V3 Reference page for information on what values ​​are returned in the arguments. Looking at the “click” in the Events table on this page, it says “Arguments: MouseEvent | IconMouseEvent”. This means that MouseEvent object or IconMouseEvent object is set and called. The IconMouseEvent object is a MouseEvent object plus an ID of a place called placeId. In fact, the arguments passed to the event listener called from the click event are IconMouseEvent when clicked on the normal map, and IconMouseEvent when the landmark is clicked.

function initMap() {
  // 地図の中心を決める
  var latlng = new google.maps.LatLng(35.388276, 139.427348);

  // 地図を表示するためのオプションを設定する
  var opt = {
    zoom: 15,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  // 地図を表示する。
  var map = new google.maps.Map(document.getElementById('map'), opt);

  // イベントリスナ(コールバック関数)
  function click_callback(e) {
    alert(e.latLng.toString());
  }

  // イベントリスナの設定
  map.addListener('click', click_callback);
}

Markers

By using the google.maps.Marker class you can set markers. See the next program. In this program, markers are created in line 16. On the 17th line, the location to place the marker is specified, and on the 18th line, the map where the marker is placed is specified. Setting an appropriate value for position allows you to set markers wherever you like.

function initMap() {
  // 地図の中心を決める
  var latlng = new google.maps.LatLng(35.388276, 139.427348);

  // 地図を表示するためのオプションを設定する
  var opt = {
    zoom: 15,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  // 地図を表示する。
  var map = new google.maps.Map(document.getElementById('map'), opt);

  // マーカーの追加
  var marker = new google.maps.Marker({
                     position: latlng,
                     map: map
		});
}

Markers also have various options, so please refer to MarkerOptions object specification.

Same origin policy as JSONP

Same generation policy

JavaScript has a restriction called the same generation policy, so that it cannot communicate with sites other than the site from which the JavaScript program was downloaded. This is the program that had been placed on the page that appears to communicate with other sites. It is a constraint on the information present in order to prevent leakage. Even the same content is judged to be from a different domain when accessing with http or https, so we must be careful.

However, the restriction that communication with the site other than the original site from which the program was downloaded is very severe. It could lead to lowering the convenience of JavaScript and is hence a double-edged sword.

Same source policy

From the JavaScript program, the same source policy can access only the site that brought the program. Conversely, if you have a JavaScript program for accessing the site you want to access, that is, the site with data, there will be no problem in accessing it. By utilizing this, it is possible to avoid the same-origin policy by preparing in advance and using a function to process the JSON, calling a function that is prepared from the site side that has the data.

For example, suppose you have the following program. Let’s assume that here the ninth line and thereafter are on different sites and will call the method with the data on that site as arguments. In this example, when the second line is executed, the function process () on line 10 is called. Then, from the function process (), func () which is a function defined by you is called with the data stored in the argument. By doing this, you can receive the data placed on another domain with the function you defined.

 

// 他のドメインにあるべき関数の呼び出し(読み込み)
process();

// 自分で定義した関数
function func(json) {
  alert(json.a + " + " + json.b + " = " + (json.a + json.b));
}

// 他のドメインにあるべき関数
function process() {
  func({ "a": 123, "b": 456 });
}

Actually it is used as follows. In this example, using the Query API of the MediaWiki API, the words beginning with “Keio” registered in WikiPedia are listed up and the top 50 is displayed. In the part of “<script src =” http://en.wikipedia.org/w/api.php?action=query&list=allpages&apfrom= Keio & aplimit = 50 & format = json & callback = func “>”, in fact it stated above a function with the data as arguments will be returned, so func () will be called. A function called from another program in this manner is called a callback function. Since how to pass the callback function depends on the Web service used, please refer to the Web service manual.

JavaScript

function func(json) {
  var ele = document.getElementById("listOfKeio");

  var i;
  for (i=0; i &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; json.query.allpages.length; i++) {
    ele.innerHTML += (i + ": " + json.query.allpages[i].title + "&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;br /&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;");
  }
}

HTML

&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;div id="listOfKeio"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/div&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;script src="myprog.js"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;script src="http://ja.wikipedia.org/w/api.php?action=query&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;list=allpages&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;apfrom=慶應&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;aplimit=50&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;format=json&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;callback=func"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

However, there are major problems in using this method to use the Web service. One can call the callback function only at the timing of accessing the Web service page, that is, the Wikipedia page with the script element. With this, it is impossible to retrieve data at the necessary timing.

Therefore, when using JSONP, generate a script element in the program as follows. In the twelfth line of the JavaScript part, a script element is newly generated and assigned to the variable o. createElement () is a method for creating a new HTML element. In line 13, the src attribute is added to the script element generated in the 12th line using the setAttribute () method. After that, in the 14th line, the generated script element is set as a child of the div element, that is, within the div element. As a result, the callback function func () is called at the timing when the script element is displayed (in fact it is not visible to the eyes but embedded in the HTML document), that is, when the button is pressed.

 

HTML部

&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;script type="text/javascript" src="myprog.js"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;button id="listKeio" onclick="getFromWikipedia()"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;List&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/button&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;div id="listOfKeio"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/div&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

JavaScript部

function func(json) {
  var ele = document.getElementById('listOfKeio');

  var i;
  for (i=0; i &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; json.query.allpages.length; i++) {
    ele.innerHTML += i + ": " + json.query.allpages[i].title + "&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;br /&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;";
  }
}

function getFromWikipedia() {
  var e = document.getElementById('listOfKeio');
  var o = document.createElement("script");
      o.setAttribute("src", "http://ja.wikipedia.org/w/api.php?action=query&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;list=allpages&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;apfrom=慶應&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;aplimit=50&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;format=json&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;callback=func");
  e.appendChild(o);
}

Exercise 11-

Please refer to the above description and create a program to display Google Map.

Exercise 11-

Based on the above explanation, display Google Map and click on the map, create a program showing the latitude and longitude of that place.

Note: You can not call https://maps.googleapis.com/maps/api/js more than once on the same page. Therefore, when creating on the same page as other exercises, care must be taken because it is necessary to combine callback functions into one.

Exercise 11-

Based on the above explanation, display Google Map and click on the map so that a map centered on that place is displayed. To change the center point of the map, use the setCenter () method of the map object. For example, if the map object is in the variable map, set it like map.setCenter (lonlat). Here, lonlat is an object containing latitude and longitude.

Note: You can not call https://maps.googleapis.com/maps/api/js more than once on the same page. Therefore, when creating on the same page as other exercises, care must be taken because it is necessary to combine callback functions into one.

Exercise 11-

Based on the above explanation, please display a Google Map and click on the map, create a program that will place a marker in that place. Also, at that time, make sure the markers are labeled “1”, “2”, “3”. Please note that the value of the label property when generating the Marker object must be a string.

Note: You can not call https://maps.googleapis.com/maps/api/js more than once on the same page. Therefore, when creating on the same page as other exercises, care must be taken because it is necessary to combine callback functions into one.

Exercise 11-

With reference to the explanation above, please create a program that displays 50 words related to Kei by pressing a button.