php+mysql开发google地图功能

2017-04-22 23:03 阅读 2,090 次 评论 0 条

主要在google地图通过单击,添加标记,然后存入到数据库中。地图版本是第三版。

1、创建数据库和表

CREATE database maps;

CREATE TABLE `markers`

(  `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,

  `name` VARCHAR( 60 ) NOT NULL , 

`address` VARCHAR( 80 ) NOT NULL , 

`lat` FLOAT( 10, 6 ) NOT NULL , 

`lng` FLOAT( 10, 6 ) NOT NULL , 

`type` VARCHAR( 30 ) NOT NULL)DEFAULT   CHARSET=gb2312;

2、新建个conn.php文件

<?php

$conn = @ mysql_connect("localhost", "root", "123456") or die("数据库链接错误");

mysql_select_db("maps", $conn);//选择maps表;

mysql_query("set names 'GBK'"); //使用GBK中文编码;

?>

3、新建个add.php文件

<?phprequire("conn.php");//调用配置文件

error_reporting(0);//去除警告信息

//将标记信息插入到数据库中

if($_POST['name']){

     if($_POST['add']){

        $query = "insert into markers (name,address,lat,lng,type) values

        ('$_POST[name]','$_POST[address]','$_POST[lat]','$_POST[lng]','bar')";

        mysql_query($query);

       }

}

?>

<html>

<head>

<meta content="text/html; charset=gb2312" http-equiv="content-type">

<script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>

<script type="text/javascript">

var geocoder;  var map;

var markersArray = [];

function initialize() {

geocoder = new google.maps.Geocoder();

var latlng = new google.maps.LatLng(32.03602,118.795166);

var myOptions = {      zoom: 11,      center: latlng,      mapTypeId: google.maps.MapTypeId.ROADMAP    }

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);        google.maps.event.addListener(map, 'click', function(event) {                                                                                                              addMarker(event.latLng);

});

}

function addMarker(location) {

<!--增加标记--!>

var clickedLocation = new google.maps.LatLng(location);

var marker = new google.maps.Marker({

position: location,

map: map

});

document.getElementById("show_x").value = location.lat();<!--获得标记的经度幷显示在文本框中--!>

document.getElementById("show_y").value = location.lng();<!--获得标记的纬度幷显示在文本框中--!>

map.setCenter(location);  markersArray.push(marker);

}

// 移除标记,但是保存在数组中

function clearOverlays() {

if (markersArray) {

for (i in markersArray) {

markersArray[i].setMap(null);

}

}

}

// 显示在数组中的标记

function showOverlays() {

if (markersArray) {

for (i in markersArray) {

markersArray[i].setMap(map);

}

}

}

// 删除标记

function deleteOverlays() {

if (markersArray) {

for (i in markersArray) {

markersArray[i].setMap(null);

}

markersArray.length = 0;

}

}

function codeAddress() {

<!--搜索功能--!>

var address = document.getElementById("address").value;

if (geocoder) {

geocoder.geocode( { 'address': address}, function(results, status) {

if (status == google.maps.GeocoderStatus.OK) {

map.setCenter(results[0].geometry.location);

var marker = new google.maps.Marker({

map: map,

position: results[0].geometry.location

});

} else {

alert("Geocode was not successful for the following reason: " + status);

}

});

}

}

</script>

<body onLoad="initialize()">

<div>

<input id="address" type="textbox" value="南京">

<input type="button" value="搜索" onClick="codeAddress()">

</div>

<div id="map_canvas" style="width: 800px; height: 500px;"></div><br/>

<form action="" method="post">

标记名称:<input type="text" name="name" size="50"  /><br/>

地址:<input type="text" name="address" size="50"  /> <br/>

经度:<input type="text" name="lat" id="show_x" size="50" ><br/>

纬度:<input type="text" name="lng" id="show_y" size="50" >

<input type="submit" name="add" value="增加标记"  />

</form>

<div>

<input onClick="clearOverlays();" type=button value="Clear Overlays"/>

<input onClick="showOverlays();" type=button value="Show All Overlays"/>

<input onClick="deleteOverlays();" type=button value="Delete Overlays"/>

</div>

</body>

</html>

 

接着将数据库的标记显示在地图上面。

1、新建个phpsqlajax_genxml.php文件

<?php
require("conn.php");
mysql_query("set names 'GBK'"); //
使用GBK中文编码;
error_reporting(0);

function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}

// 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;charset=gb2312");

// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';

?>


2
、新建主页index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312"/>
<title>Google Maps AJAX + MySQL/PHP Example</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAjU0EJWnWPMv7oQ-
jjS7dYxTPZYElJSBeBUeMSX5xXgq6lLjHthSAk20WnZ_iuuzhMt60X_ukms-AUg"
type="text/javascript"></script>
<script src="labeledmarker.js"></script>
<script type="text/javascript">

//<![CDATA[
var iconBlue = new GIcon();
iconBlue.image = 'http://gmaps-samples.googlecode.com/svn/trunk/markers/circular/greencirclemarker.png';
iconBlue.shadow = '';
iconBlue.iconSize = new GSize(32, 32);
iconBlue.shadowSize = new GSize(22, 20);
iconBlue.iconAnchor = new GPoint(16, 16);
iconBlue.infoWindowAnchor = new GPoint(5, 1);

var iconRed = new GIcon();
iconRed.image = 'http://gmaps-samples.googlecode.com/svn/trunk/markers/circular/bluecirclemarker.png';
iconRed.shadow = '';
iconRed.iconSize = new GSize(32, 32);
iconRed.shadowSize = new GSize(22, 20);
iconRed.iconAnchor = new GPoint(16, 16);
iconRed.infoWindowAnchor = new GPoint(5, 1);

var customIcons = [];
customIcons["restaurant"] = iconBlue;
customIcons["bar"] = iconRed;
var markerGroups = { "restaurant": [], "bar": []};

function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(32.03602,118.795166), 11);

GDownloadUrl("phpsqlajax_genxml2.php", function(data) {
var xml = GXml.parse(data);
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 GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, name, address, type);
map.addOverlay(marker);
}
});
}
}

function createMarker(point, name, address, type) {
var marker = new LabeledMarker(point, {icon: customIcons[type], labelText: name, labelOffset: new GSize(-6, -10)});
markerGroups[type].push(marker);
var html = "<b>" + name + "</b> <br/>" + address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
//]]>
</script>

</head>

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


3
、另外有个JS文件labeledmarker.js,这个文件主要是关于标记样式、信息的,里面有注释,不过是英文的。

/*
* LabeledMarker Class, v1.2
*
* Copyright 2007 Mike Purvis (http://uwmike.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This class extends the Maps API's standard GMarker class with the ability
* to support markers with textual labels. Please see articles here:
*
*       http://googlemapsbook.com/2007/01/22/extending-gmarker/
*       http://googlemapsbook.com/2007/03/06/clickable-labeledmarker/
*/

/**
* Constructor for LabeledMarker, which picks up on strings from the GMarker
* options array, and then calls the GMarker constructor.
*
* @param {GLatLng} latlng
* @param {GMarkerOptions} Named optional arguments:
*   opt_opts.labelText {String} text to place in the overlay div.
*   opt_opts.labelClass {String} class to use for the overlay div.
*     (default "LabeledMarker_markerLabel")
*   opt_opts.labelOffset {GSize} label offset, the x- and y-distance between
*     the marker's latlng and the upper-left corner of the text div.
*/
function LabeledMarker(latlng, opt_opts){
this.latlng_ = latlng;
this.opts_ = opt_opts;

this.labelText_ = opt_opts.labelText || "";
this.labelClass_ = opt_opts.labelClass || "LabeledMarker_markerLabel";
this.labelOffset_ = opt_opts.labelOffset || new GSize(0, 0);

this.clickable_ = opt_opts.clickable || true;
this.title_ = opt_opts.title || "";
this.labelVisibility_  = true;

if (opt_opts.draggable) {
// This version of LabeledMarker doesn't support dragging.
opt_opts.draggable = false;
}

GMarker.apply(this, arguments);
};

// It's a limitation of JavaScript inheritance that we can't conveniently
// inherit from GMarker without having to run its constructor. In order for
// the constructor to run, it requires some dummy GLatLng.
LabeledMarker.prototype = new GMarker(new GLatLng(0, 0));

/**
* Is called by GMap2's addOverlay method. Creates the text div and adds it
* to the relevant parent div.
*
* @param {GMap2} map the map that has had this labeledmarker added to it.
*/
LabeledMarker.prototype.initialize = function(map) {
// Do the GMarker constructor first.
GMarker.prototype.initialize.apply(this, arguments);

this.map_ = map;
this.div_ = document.createElement("div");
this.div_.className = this.labelClass_;
this.div_.innerHTML = this.labelText_;
this.div_.style.position = "absolute";
this.div_.style.cursor = "pointer";
this.div_.title = this.title_;

map.getPane(G_MAP_MARKER_PANE).appendChild(this.div_);

if (this.clickable_) {
/**
* Creates a closure for passing events through to the source marker
* This is located in here to avoid cluttering the global namespace.
* The downside is that the local variables from initialize() continue
* to occupy space on the stack.
*
* @param {Object} object to receive event trigger.
* @param {GEventListener} event to be triggered.
*/
function newEventPassthru(obj, event) {
return function() {
GEvent.trigger(obj, event);
};
}

// Pass through events fired on the text div to the marker.
var eventPassthrus = ['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mouseout'];
for(var i = 0; i < eventPassthrus.length; i++) {
var name = eventPassthrus[i];
GEvent.addDomListener(this.div_, name, newEventPassthru(this, name));
}
}
};

/**
* Call the redraw() handler in GMarker and our our redrawLabel() function.
*
* @param {Boolean} force will be true when pixel coordinates need to be recomputed.
*/
LabeledMarker.prototype.redraw = function(force) {
GMarker.prototype.redraw.apply(this, arguments);
this.redrawLabel_();
};

/**
* Moves the text div based on current projection and zoom level.
*/
LabeledMarker.prototype.redrawLabel_ = function() {
// Calculate the DIV coordinates of two opposite corners of our bounds to
// get the size and position of our rectangle
var p = this.map_.fromLatLngToDivPixel(this.latlng_);
var z = GOverlay.getZIndex(this.latlng_.lat());

// Now position our div based on the div coordinates of our bounds
this.div_.style.left = (p.x + this.labelOffset_.width) + "px";
this.div_.style.top = (p.y + this.labelOffset_.height) + "px";
this.div_.style.zIndex = z; // in front of the marker
};

/**
* Remove the text div from the map pane, destroy event passthrus, and calls the
* default remove() handler in GMarker.
*/
LabeledMarker.prototype.remove = function() {
GEvent.clearInstanceListeners(this.div_);
if (this.div_.outerHTML) {
this.div_.outerHTML = ""; //prevent pseudo-leak in IE
}
if (this.div_.parentNode) {
this.div_.parentNode.removeChild(this.div_);
}
this.div_ = null;
GMarker.prototype.remove.apply(this, arguments);
};

/**
* Return a copy of this overlay, for the parent Map to duplicate itself in full. This
* is part of the Overlay interface and is used, for example, to copy everything in the
* main view into the mini-map.
*/
LabeledMarker.prototype.copy = function() {
return new LabeledMarker(this.latlng_, this.opts_);
};

/**
* Shows the marker, and shows label if it wasn't hidden. Note that this function
* triggers the event GMarker.visibilitychanged in case the marker is currently hidden.
*/
LabeledMarker.prototype.show = function() {
GMarker.prototype.show.apply(this, arguments);
if (this.labelVisibility_) {
this.showLabel();
} else {
this.hideLabel();
}
};

/**
* Hides the marker and label if it is currently visible. Note that this function
* triggers the event GMarker.visibilitychanged in case the marker is currently visible.
*/
LabeledMarker.prototype.hide = function() {
GMarker.prototype.hide.apply(this, arguments);
this.hideLabel();
};

/**
* Repositions label and marker when setLatLng is called.
*/
LabeledMarker.prototype.setLatLng = function(latlng) {
this.latlng_ = latlng;
GMarker.prototype.setLatLng.apply(this, arguments);
this.redrawLabel_();
};

/**
* Sets the visibility of the label, which will be respected during show/hides.
* If marker is visible when set, it will show or hide label appropriately.
*/
LabeledMarker.prototype.setLabelVisibility = function(visibility) {
this.labelVisibility_ = visibility;
if (!this.isHidden()) { // Marker showing, make visible change
if (this.labelVisibility_) {
this.showLabel();
} else {
this.hideLabel();
}
}
};

/**
* Returns whether label visibility is set on.
* @return {Boolean}
*/
LabeledMarker.prototype.getLabelVisibility = function() {
return this.labelVisibility_;
};

/**
* Hides the label of the marker.
*/
LabeledMarker.prototype.hideLabel = function() {
this.div_.style.visibility = 'hidden';
};

/**
* Shows the label of the marker.
*/
LabeledMarker.prototype.showLabel = function() {
this.div_.style.visibility = 'visible';
};

以上就是使用php+mysql在Google地图上实现的一些基本操作功能。

版权声明:本文著作权归原作者所有,欢迎分享本文,谢谢支持!
转载请注明:php+mysql开发google地图功能 | 雨晨博客
分类:PHP, 程序笔记 标签:, ,

发表评论


表情