简体   繁体   English

如何将Google AP3地图置于标记中心?

[英]How to center google ap3 map on marker?

I am developing a real estates website where the admin can add properties to his projects page. 我正在开发一个房地产网站,管理员可以在其中向他的项目页面添加属性。 Now one of the options he should have is to add the place of the property he advertised. 现在,他应该拥有的选择之一是添加他所宣传的房产的位置。 On my CMS pan I have the map which the admin will drop his pin to his specific property and then save this. 在我的CMS面板上,我有地图,管理员可以将其图钉放到他的特定属性,然后保存。 After that the expected clients who will enter the site will see the pin which the admin put before. 之后,将要进入站点的预期客户将看到管理员之前放置的密码。

Here is my code of the admin section 这是我的管理部分的代码

HTML code HTML代码

<!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=true"></script>
    <script type="text/javascript">
    var marker;
    var infowindow;

    function initialize() {
      var latlng = new google.maps.LatLng(30.0599153,31.2620199,13);
      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: 800px; height: 600px"></div>
    <div id="message"></div>
  </body>

</html>

And then it comes to the PHP code which manage the dynamic part of adding the information to the database: 然后是PHP代码,该代码管理将信息添加到数据库的动态部分:

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

mysql_connect("localhost", "root", "") or
         die("Could not connect: " . mysql_error());
mysql_select_db("arabia");

// 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());
}

?>

Now come to the clients section. 现在进入客户部分。

The HTML of the client section which has the problem, the clients sees the map from here 有问题的客户端部分的HTML,客户端从这里看到地图

<!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>map</title>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    //<![CDATA[

    var customIcons = {
      restaurant: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
      },
      bar: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
      }
    };
    function load() {
      var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(30.0599153,31.2620199,13)||map.setCenter(marker.getPosition()),
        zoom: 13,
        mapTypeId: 'roadmap'
      });
      var infoWindow = new google.maps.InfoWindow;

      // Change this depending on the name of your PHP file
      downloadUrl("phpsqlajax_genxml.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var name = markers[i].getAttribute("name");
          var address = markers[i].getAttribute("address");
          var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
          var html = "<b>" + name + "</b> <br/>" + address;
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon
          });
          bindInfoWindow(marker, map, infoWindow, html);
        }
      });
    }

    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    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, request.status);
        }
      };

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

    function doNothing() {}

    //]]>

  </script>

  </head>

  <body onload="load()">
    <div id="map" style="width: 500px; height: 300px"></div>
  </body>

</html>

Now the last PHP section witch manage getting the data from the database: 现在,最后一个PHP部分将管理从数据库中获取数据:

<?php  

// Start XML file, create parent node

$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node); 

// Opens a connection to a MySQL server

mysql_connect("localhost", "root", "") or
         die("Could not connect: " . mysql_error());
mysql_select_db("arabia");

// Select all the rows in the markers table

$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {  
  die('Invalid query: ' . mysql_error());
} 

header("Content-type: text/xml"); 

// Iterate through the rows, adding XML nodes for each

while ($row = @mysql_fetch_assoc($result)){  
  // ADD TO XML DOCUMENT NODE  
  $node = $dom->createElement("marker");  
  $newnode = $parnode->appendChild($node);   
  $newnode->setAttribute("name",$row['name']);
  $newnode->setAttribute("address", $row['address']);  
  $newnode->setAttribute("lat", $row['lat']);  
  $newnode->setAttribute("lng", $row['lng']);  
  $newnode->setAttribute("type", $row['type']);
} 

echo $dom->saveXML();

?>

Now everything is running fine with this code the whole problem is in this line of code in the HTML of the client view center: 现在,使用此代码,一切运行正常,整个问题出在客户端视图中心的HTML中的以下代码行中:

new google.maps.LatLng(30.0599153,31.2620199,13)||map.setCenter(marker.getPosition()), 新的google.maps.LatLng(30.0599153,31.2620199,13)|| map.setCenter(marker.getPosition()),

which I need it to be centered on the pin that the admin put before. 我需要它以管理员之前放置的引脚为中心。

Update: This part of answer is valid only for admin side. 更新:答案的这一部分仅对管理员有效。

Update map click handler with map.setCenter(event.latLng); 使用map.setCenter(event.latLng);更新地图点击处理程序map.setCenter(event.latLng); :

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

    map.setCenter(event.latLng);

    google.maps.event.addListener(marker, "click", function() {
      infowindow.open(map, marker);
    });
});

Update: This part of answer is for client side. 更新:答案的这一部分是针对客户端的。

Map has to be initialized like: 地图必须像这样初始化:

  var map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(30.0599153,31.2620199,13),
    zoom: 13,
    mapTypeId: 'roadmap'
  });

If you have only one marker than you should use method setCenter() like (part of for loop): 如果只有一个标记,则应使用setCenter()方法,例如( for循环的一部分):

          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon
          });
          map.setCenter(point);

If you have many markers than you can use method fitBounds() , changes in for loop: 如果标记数量超出可使用方法fitBounds() ,则更改for循环:

    var latlngBounds = new google.maps.LatLngBounds();

    for (var i = 0; i < markers.length; i++) {
          var name = markers[i].getAttribute("name");
          var address = markers[i].getAttribute("address");
          var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
          var html = "<b>" + name + "</b> <br/>" + address;
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon
          });

          latlngBounds.extend(point);

          bindInfoWindow(marker, map, infoWindow, html);
    }

    map.fitBounds(latlngBounds);

That way map will be set so all markers are visible. 这样将设置地图,以便所有标记都可见。

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

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