简体   繁体   English

将Google Maps Markers onClick保存到数据库

[英]Save Google Maps Markers onClick To Database

I want your guys' help on this. 我希望你们能帮上忙。 I wrote the code for allowing users to create markers(with infowindow) with a 'click' function that will save the lat/lan and other info to a MySQL database that will then be called to show the markers on the map. 我编写了允许用户使用“单击”功能创建标记(带有信息窗口)的代码,该功能会将纬度/经度和其他信息保存到MySQL数据库中,然后该数据库将被调用以在地图上显示标记。 When you click on the map, it creates a marker but it will not save the info in the infowindow to the database. 当您单击地图时,它会创建一个标记,但不会将信息窗口中的信息保存到数据库中。 I followed the guide from the google maps developer's guide but I still can't get it to work. 我遵循了Google Maps开发人员指南中的指南,但仍然无法正常工作。 I even triple checked to make sure my MySQL login details work correct and still nothing. 我什至进行了三重检查,以确保我的MySQL登录详细信息正确无误。

Here is the code to the map itself: 这是地图本身的代码:

    <!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(37.4419, -122.1419);
  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>Name:</td> <td><input type='text' id='name'/> </td> </tr>" +
             "<tr><td>Address:</td> <td><input type='text' id='address'/></td> </tr>" +
             "<tr><td>Type:</td> <td><select id='type'>" +
             "<option value='bar' SELECTED>bar</option>" +
             "<option value='restaurant'>restaurant</option>" +
             "</select> </td></tr>" +
             "<tr><td></td><td><input type='button' value='Save & Close'     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 name = escape(document.getElementById("name").value);
  var address = escape(document.getElementById("address").value);
  var type = document.getElementById("type").value;
  var latlng = marker.getPosition();

  var url = "phpsqlinfo_addrow.php?name=" + name + "&address=" + address +
            "&type=" + type + "&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: 500px; height: 300px"></div>
<div id="message"></div>
</body>

</html>

This is what is supposed to save info to the database(phpsqlinfo_addrow.php): 这是将信息保存到数据库的内容(phpsqlinfo_addrow.php):

    <?php
require("phpsqlinfo_dbinfo.php");

// Gets data from URL parameters
$name = $_GET['name'];
$address = $_GET['address'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
$type = $_GET['type'];

// Opens a connection to a MySQL server
$connection=mysql_connect ("localhost", $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}

// Insert new row with user data
$query = sprintf("INSERT INTO markers " .
     " (id, name, address, lat, lng, type ) " .
     " VALUES (NULL, '%s', '%s', '%s', '%s', '%s');",
     mysql_real_escape_string($name),
     mysql_real_escape_string($address),
     mysql_real_escape_string($lat),
     mysql_real_escape_string($lng),
     mysql_real_escape_string($type));

$result = mysql_query($query);

if (!$result) {
  die('Invalid query: ' . mysql_error());
}

?>

hi i have same issue with my project to save customer location, which they click on there browser, what i did was i save location in latitude and longitude in two input box as{you may take it hidden so it will not seen} in and give submit button and submit form i have given code you can also change it to submit form on click on map by submitting form on click by this and you can also store latitude and longitude in same column if you want 嗨,我在保存客户位置的项目中遇到了同样的问题,他们在那点击浏览器,我所做的是我在两个输入框中将位置保存在纬度和经度中,因为{您可能将其隐藏起来,所以看不到}在给提交按钮并提交表单我已经给出了代码,您也可以将其更改为在地图上单击时通过在单击时提交表单来提交表单,也可以将纬度和经度存储在同一列中(如果需要)

and you will need to insert you key 然后您需要插入钥匙

document.getElementById("yourform").submit();



<html>
<head>
    <style type="text/css">
              #map_canvas {height:300px;width:500px}
    </style>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=""""youerapikeyhere""""&language=mr"></script>
  <script type="text/javascript">
        var map;
        var marker;
        var markersArray = [];
        function initialize()
        {
            var latlng = new google.maps.LatLng(18.5236, 73.8478);
                var mapOptions = {
                zoom: 13,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    google.maps.event.addListener(map, 'click', function(event) {
    if (marker) {
    marker.setMap(null);    //code          
    }
        //adding marker
    document.getElementById('txtLat').value=event.latLng.lat();
    document.getElementById('txtLng').value=event.latLng.lng();
      marker= new google.maps.Marker({
      position: event.latLng,
      map: map,
      title: 'pune'
  });
      //creting info window instance
      var infowindow = new google.maps.InfoWindow({
      content: 'selected location'
  });
      //adding pointer click event to open infowindow
    google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>

        <table cellpadding="0" cellspacing="0">
            <tr><td colspan=3><div id="map_canvas" style="background-color: #ffffff"></div></td></tr>
            <tr><td><input type="text" id="txtLat" name="txtLat"style="width:150px"></td>
                <td><input type="text" id="txtLng" name="txtLng"style="width:150px"></td></tr>
        </table></form>
</html>`

Try to narrow down the possibilities, or at least find out "where" it went wrong; 尝试缩小可能性,或者至少找出问题出在哪里。 meaning, is the issue caused from the front end or in the backend!? 意思是问题是由前端引起的还是由后端引起的?

If you use Webkit UA (browser) or its variants, use its Developer tools; 如果您使用Webkit UA(浏览器)或其变体,请使用其Developer工具; if using Firefox, install an AddOn called FireBug. 如果使用Firefox,请安装一个名为FireBug的插件。 In the marker's click handler, try to output the coordinates using alert() or console.log() and see if the results are accurately fetched. 在标记的单击处理程序中,尝试使用alert()或console.log()输出坐标,并查看结果是否准确获取。 Next check whether the AJAX call is passed as it should be to the backend. 接下来,检查是否将AJAX调用按原样传递给后端。

In your PHP, try to examine the incoming values (from request parameters). 在您的PHP中,尝试检查传入的值(来自请求参数)。 Also turn on the debug output in php.ini so you'll know if the DB connections are successfully made by checking stderr or system logs. 还要在php.ini中打开调试输出,以便通过检查stderr或系统日志来了解数据库连接是否成功完成。

There's a lot of things that could go wrong. 有很多事情可能出错。 It's hard to tell given by the lack of details you provided, but I hope my reply helps you to get a good start. 您所提供的详细信息很难告诉您,但我希望我的回复能帮助您获得一个良好的开端。

Oh, BTW, I'd strongly suggest you switch to PDO over mysql_ , the mysql_ are to be deprecated in the future. 哦,顺便说一句,我强烈建议您通过mysql_切换到PDO,以后将不建议使用mysql_

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM