dongsimang4036 2014-05-14 08:11 采纳率: 100%
浏览 33

Google api v3 - 从信息窗口到json txt文件:保存用户添加的表单数据

I make google map api v3. I want to make saving user-added form data by clicking on the marker, it appears info window, info window contains form data, then data added will be saved in json txt file. Here is map.html code

<!DOCTYPE html >
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Google Maps JavaScript API v3 Example: Map Simple</title>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    var marker;
    var infowindow;

    function initialize() {
      var latlng = new google.maps.LatLng(-6.9667, 110.41677);
      var options = {
    zoom: 13,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById("map-canvas"), options);
      var html = "<table>" +
             "<tr> <td> Title:</td> <td><input type='text' name='title' id='title'/> </td> </tr>  " +
         "<tr> <td> Description:</td> <td><input type='text' name='description' id='description'/> </td> </tr> " +
         "<tr> <td> Category:</td> <td><input type='text' name='category' id='category'/> </td> </tr> " +
             "<tr> <td></td> <td> <input type='submit' id='submit' value='Submit' onclick='saveData()' /> </td> </tr> ";
    infowindow = new google.maps.InfoWindow({
     content: html
    });

    google.maps.event.addListener(map, "click", function(event) {
    marker = new google.maps.Marker({
      position: event.latLng,
      map: map
    });
    google.maps.event.addListener(marker, "click", function() {
      infowindow.open(map, marker);
    });
    });
    }

    function saveData() {
      var title = escape(document.getElementById("title").value);
      var description = escape(document.getElementById("description").value);
      var category = escape(document.getElementById("category").value);
      var latlng = marker.getPosition();

      var url = "save_json.php?title=" + title + "&description=" + description +
            "&category=" + category + "&lat=" + latlng.lat() + "&lng=" + latlng.lng();
      downloadUrl(url, function(data, responseCode) {
    if (responseCode == 200 && data.length <= 1) {
      infowindow.close();
      document.getElementById("message").innerHTML = "Location added.";
    }
      });
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

      request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request.responseText, request.status);
    }
      };

      request.open('GET', url, true);
      request.send(null);
    }

    function doNothing() {}
    </script>
  </head>

  <body style="margin:0px; padding:0px;" onload="initialize()">
    <div id="map-canvas" style="width: 800px; height: 500px"></div>
    <div id="message"></div>
  </body>

</html>

Here is save_json.php

<?php
    // Append new form data in json string saved in text file

    // path and name of the file
$filetxt = 'dirdata/data.txt';

    // check if all form data are submited, else output error message
    if(isset($_POST['title']) && isset($_POST['lat']) && isset($_POST['lng']) && isset($_POST['description']) && isset($_POST['category'])) {
    // if form fields are empty, outputs message, else, gets their data
    if(empty($_POST['title']) || empty($_POST['lat']) || empty($_POST['lng']) || empty($_POST['description']) || empty($_POST['category'])) {
        echo 'All fields are required';
    }
    else {
    // gets and adds form data into an array
    $data = array(
      'title'=> $_POST['title'],
      'lat'=> (float) $_POST['lat'],
      'lng'=> (float) $_POST['lng'],
      'description'=> $_POST['description'],
      'category'=> $_POST['category'],
    );

    // path and name of the file
    $filetxt = 'dirdata/data.txt';

    $arr_data = array();        // to store all form data

    // check if the file exists
    if(file_exists($filetxt)) {
      // gets json-data from file
      $jsondata = file_get_contents($filetxt);

      // converts json string into array
      $arr_data = json_decode($jsondata, true);
    }

    // appends the array with new form data
    $arr_data[] = $data;

    // encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
    $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

    // saves the json string in "data.txt" (in "dirdata" folder)
    // outputs error message if data cannot be saved
    if(file_put_contents('dirdata/data.txt', $jsondata)) echo 'Data successfully saved';
    else echo 'Tidak dapat menyimpan data di "dirdata/data.txt"';
  }
}
    else echo 'Form fields not submited';
?>

The data should be saved in data.txt like this, but it it doesn't work

[
    {
    "title": "title",
    "lat": -6.9000,
    "lng": -110.000,
    "description": "description",
    "category": "category"
    }
]

Anyone can help me how to make it correct? Thank you very much for any help

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
    • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
    • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
    • ¥15 如何在炒股软件中,爬到我想看的日k线
    • ¥15 seatunnel 怎么配置Elasticsearch
    • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
    • ¥15 (标签-MATLAB|关键词-多址)
    • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
    • ¥500 52810做蓝牙接受端
    • ¥15 基于PLC的三轴机械手程序