如何设置缩放级别并将地图中心映射到用户提交的位置

如何设置缩放级别并将地图中心映射到用户提交的位置

本文介绍了Google Maps API v3:如何设置缩放级别并将地图中心映射到用户提交的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我使用Google的这篇教程构建了一个web应用程序,该应用程序可以从用户输入的位置中找到最近的商店: http://code.google.com/apis/maps/articles/phpsqlsearch_v3.html 我的应用几乎按照我的要求工作,在页面加载时,地图被加载,居中并设置为缩放级别6,用户使用他们的位置填写表单。 然后,应用程序从数据库中提取所有商店信息,并用每个标记填充地图。 缩放级别似乎 我实际上想要提交的内容是放大到缩放级别6,然后将地图居中放置到用户输入位置的经纬度和最近商店的输出信息,例如最近的5个。我想知道这里有没有人知道如何实现这个功能? 指数.php < div> < input type =textid =addressInputsize =50/> < input type =hiddenid =radiusSelectvalue =5/> < input type =buttononclick =searchLocations()value =Search/> < / div> < div>< select id =locationSelectstyle =width:100%; visibility:hidden>< / select>< / div> < div id =mapstyle =width:100%; height:50%>< / div> < script type =text / javascriptsrc =https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery .min.js>< /脚本> < script src =http://maps.google.com/maps/api/js?sensor=falsetype =text / javascript>< / script> < script type =text / javascript> //<![CDATA [ var map; var markers = []; var infoWindow; var locationSelect; 函数load(){ map = new google.maps.Map(document.getElementById(map),{ center:new google.maps.LatLng(54.600939134593 ,-2.399894114594), zoom:6, mapTypeId:'roadmap', mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU} }); infoWindow = new google.maps.InfoWindow(); locationSelect = document.getElementById(locationSelect); locationSelect.onchange = function(){ var markerNum = locationSelect.options [locationSelect.selectedIndex] .value; if(markerNum!=none){ google.maps.event.trigger(markers [markerNum],'click'); } }; 函数searchLocations(){ var address = document.getElementById(addressInput)。value; var geocoder = new google.maps.Geocoder(); geocoder.geocode({address:address},function(results,status){ if(status == google.maps.GeocoderStatus.OK){ searchLocationsNear(results [0]。 geometry.location); } else { alert(address +'not found'); } }); } 函数clearLocations(){ infoWindow.close(); for(var i = 0; i< markers.length; i ++){ markers [i] .setMap(null); } markers.length = 0; locationSelect.innerHTML =; var option = document.createElement(option); option.value =none; option.innerHTML =查看所有结果:; locationSelect.appendChild(option); 函数searchLocations近(中){ clearLocations(); var radius = document.getElementById('radiusSelect')。value; var searchUrl ='phpsqlsearch_genxml.php?lat ='+ center.lat()+'& lng ='+ center.lng()+'& radius ='+ radius; downloadUrl(searchUrl,function(data){ var xml = parseXml(data); var markerNodes = xml.documentElement.getElementsByTagName(marker); var bounds =新的google.maps.LatLngBounds(); (var i = 0; i< markerNodes.length; i ++){ var town = markerNodes [i] .getAttribute(town); var postcode = markerNodes [i] .getAttribute(postcode); var name = markerNodes [i] .getAttribute(name); var address = markerNodes [i] .getAttribute (address); var distance = parseFloat(markerNodes [i] .getAttribute(distance)); var latlng = new google.maps.LatLng( parseFloat(markerNodes [ i] .getAttribute(lat)), parseFloat(markerNodes [i] .getAttribute(lng))); var id = markerNodes [i] .getAttribute( id); var fname = markerNodes [i] .getAttribute(fname); var link ='< a href =http://www.domain.co.uk/stores /'+ fname +' - '+ id +'.htmltarget =_ b lanktitle =Store:'+ town +'>更多信息< / a>'; createOption(name,distance,i); createMarker(latlng,name,address,town,postcode,link); bounds.extend(latlng); } map.fitBounds(bounds); locationSelect.style.visibility =visible; locationSelect.onchange = function(){ var markerNum = locationSelect.options [locationSelect.selectedIndex] .value; google.maps.event.trigger(标记[markerNum],'点击'); }; }); } 函数createMarker(latlng,name,address,town,postcode,link){ var html =< b> +城镇+< / b>< br /> +地址+< br /> +邮编+< br /> +链接; var marker = new google.maps.Marker({ map:map, position:latlng }); google.maps.event.addListener(marker,'click',function(){ infoWindow.setContent(html); infoWindow.open(map,marker); }); markers.push(marker); 函数createOption(name,distance,num){ var option = document.createElement(option); option.value = num; option.innerHTML = name +(+ distance.toFixed(1)+); locationSelect.appendChild(option); } 函数downloadUrl(url,callback){ var request = window.ActiveXObject? new ActiveXObject('Microsoft.XMLHTTP'): new XMLHttpRequest; request.onreadystatechange = function(){ if(request.readyState == 4){ request.onreadystatechange = doNothing; 回调(request.responseText,request.status); } }; request.open('GET',url,true); request.send(null); 函数parseXml(str){ if(window.ActiveXObject){ var doc = new ActiveXObject('Microsoft.XMLDOM'); doc.loadXML(str); return doc; } else if(window.DOMParser){ return(new DOMParser).parseFromString(str,'text / xml'); } } 函数doNothing(){} //]]> < / script> < script type =text / javascript> $(document).ready(function(){ load(); }); < / script> phpsqlsearch_genxml.php <?php $ db_conn = mysql_connect('xxx.xxx.xx.xx','xxxxxxxx','xxxxxx')或die('error' ); mysql_select_db('uk_db',$ db_conn)或死(mysql_error()); //从URL获取参数 $ center_lat = $ _GET [lat]; $ center_lng = $ _GET [lng]; $ radius = $ _GET [radius]; if(!$ _ GET ['zoom']){ $ _GET ['zoom'] = 11; } //启动XML文件,创建父节点 $ dom = new DOMDocument(1.0); $ node = $ dom-> createElement(markers); $ parnode = $ dom-> appendChild($ node); //选择标记表中的所有行 $ query ='SELECT address1,address2,address3,longitude,latitude,name,town,store_id,postcode,storenumber FROM uk_store WHERE isActive = 1'; if($ _ GET [region]!=''){ $ query。='AND region ='。$ _GET [region]。'''; (苏格兰,英格兰,威尔士,北爱尔兰)的AND区域; } //让我们开始检查在上搜索的内容if($ _ GET ['postcode']!=''){ //确保邮编仅包含数字字母和空格 $ searchparams。='邮编='。 $ _GET ['邮编']。 &放大器;放大器;; $ postcode = $ _GET ['postcode']; $ postcode = verifyInput($ postcode); $ query。=AND postcode ='。 $邮政编码。 ; $ b if($ _ GET ['town']!=''){ //确保城镇只有字母或空格。 $ searchparams。='town ='。 $ _GET ['town']。 &放大器;放大器;; $ town = $ _GET ['town']; $ town = verifyInput($ town); $ query。=AND town ='。 $镇。 ; if($ _ GET ['min_lat']&& $ _GET ['min_long']&&& $ _GET ['max_lat']&& $ _GET ['max_long']){ $ query。=AND latitude BETWEEN。 $ _GET ['min_lat']。 和。 $ _GET ['max_lat']。 和经度BETWEEN。 $ _GET ['min_long']。 和。 $ _GET ['max_long']; $ mapsearch = 1; $! $ b $ if(!($ _ GET ['postcodeLat']&&& $ _GET ['postcodeLong'])){ $ query。=ORDER BY Region ,镇,名称; } $ result = mysql_query($ query); if(!$ result){ die(Invalid query:。mysql_error()); } header(Content-type:text / xml); echo'< markers>'; if($ _ GET ['postcodeLat']&&&& $ _GET ['postcodeLong']) { $ count = 0; //我们需要按照距离排序结果,而$ row = @mysql_fetch_array($ result,MYSQL_ASSOC)) { $ address = $ row ['地址1'] 。 ''。 $ row ['address2']。 ''。 $行[地址3’ ]; $ distance = distance($ _ GET ['postcodeLat'],$ _GET ['postcodeLong'],$ row ['latitude'],$ row ['longitude']); $ row ['distance'] = number_format($ distance,2); $ row ['fname'] = $ row ['town']。 ' - '。 $行[名称]; $ row ['fname'] = str_replace(','',$ row ['fname']); $ row ['fname'] = ereg_replace('',' - ',$ row ['fname']); $ row ['fname'] = ereg_replace('\ /',' - ',$ row ['fname']); $ row ['fname'] = ereg_replace('\(','',$ row ['fname']); $ row ['fname'] = ereg_replace('\) ','',$ row ['fname']); $ row ['fname'] = strtolower($ row ['fname']); //获得距离并添加到$ row数组 $ results [$ distance。$ row ['id']] = $ row; } ksort($ results); foreach($ results as $ key => $ row) { //添加到XML DOCUMENT NODE $ address = $ row ['address1' ]。 ''。 $ row ['address2']。 ''。 $行[地址3’ ]; echo'< marker'; echo'name =''。parseToXML($ row ['name'])。'''; echo'fname =''。parseToXML($ row ['fname'])。'''; echo'town =''。parseToXML($ row ['town'])。'''; echo'lat ='。$ row ['latitude']。'''; echo'lng =''。$ row ['longitude']。'''; echo'id =''。$ row ['store_id']。'''; echo'address =''。$ address。''; echo'distance ='。$ row ['distance']。''; echo'postcode =''。$ row ['postcode']。''; echo'storenumber =''。$ row ['storenumber']。'''; echo'address1 =''。parsetoXml($ row ['address1'])。'''; echo'address2 =''。parsetoXml($ row ['address2'])。'''; echo'address3 =''。parsetoXml($ row ['address3'])。'''; echo'/>'; } else { //遍历行,为每个打印XML节点while($ row = @ mysql_fetch_assoc($ result)) { $ address = $ row ['address1']。 ''。 $ row ['address2']。 ''。 $行[地址3’ ]; $ row ['fname'] = $ row ['town']。 ' - '。 $行[名称]; $ row ['fname'] = ereg_replace('',' - ',$ row ['fname']); $ row ['fname'] = ereg_replace('\ /',' - ',$ row ['fname']); $ row ['fname'] = ereg_replace('\(','',$ row ['fname']); $ row ['fname'] = ereg_replace('\) ','',$ row ['fname']); //添加到XML文档节点 echo'< marker'; echo'name =''。parseToXML($ row ['name'])。'''; echo'fname =''。strtolower(parseToXML($ row ['fname']))。'''; echo'town =''。parseToXML($ row ['town'])。'''; echo'lat ='。$ row ['latitude']。'''; echo'lng =''。$ row ['longitude']。'''; echo'id =''。$ row ['store_id']。'''; echo'isSurg =''。$ row ['isLaserSurgery']。''; echo'isCons =''。$ row ['isLaserConsult']。'''; echo'address =''。parsetoXml($ address)。'''; echo'address1 =''。parsetoXml($ row ['address1'])。'''; echo'address2 =''。parsetoXml($ row ['address2'])。'''; echo'address3 =''。parsetoXml($ row ['address3'])。'''; echo'postcode =''。$ row ['postcode']。''; echo'storenumber =''。$ row ['storenumber']。'''; echo'/>'; } } //结束XML文件 echo'< / markers>'; //确保数据是xml友好的函数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; } //计算任意两点之间的距离(英里或公里)函数距离($ lat1,$ lon1,$ lat2,$ lon2,$ unit =''){ $ theta = $ lon1 - $ lon2; $ dist = sin(deg2rad($ lat1))* sin(deg2rad($ lat2))+ cos(deg2rad($ lat1))* cos(deg2rad($ lat2))* cos(deg2rad($ theta)) ; $ dist = acos($ dist); $ dist = rad2deg($ dist); $ miles = $ dist * 60 * 1.1515; if($ unit! ='') { $ unit = strtoupper($ unit); } if($ unit ==K){ ($ miles * 1.609344); } else if($ unit ==N){ return($ miles * 0.8684); } else { return $英里; } } 函数VerifyInput($ input,$ forceInt = false){ if(is _numeric($ input)){ return $ input; } elseif(!$ forceInt){ if(get_magic_quotes_gpc()&& trim(ini_get(magic_quotes_sybase))==){ $ input = stripslashes($ input); $ input = str_replace(',,$ input); $ input = str_replace(`,,$ input); } elseif(!get_magic_quotes_gpc()){ $ input = str_replace(',,$ input); $ input = str_replace(`,,$ input); } 返回$ input; } elseif($ forceInt){ return 0; } } ?> 道歉,这里有很多粘贴的内容,但我认为包括所有内容会更好,能够回答,因为没有足够的细节。 更新 我曾尝试将这段代码插入到 searchLocations 函数中,但似乎并没有改变行为: 函数searchLocations(){ var address = document.getElementById(addressInput)。value; var geocoder = new google.maps.Geocoder(); geocoder.geocode({address:address},function(results,status){ if(status == google.maps.GeocoderStatus.OK){ searchLocationsNear(results [0]。 geometry.location); /////////////// new code var myOptions = { zoom:11, center:address。 geometry.location, mapTypeId:google.maps.MapTypeId.TERRAIN } map = new google.maps.Map(document.getElementById(map),myOptions); //////////////// } else { alert(address +'not found'); } }); 解决方案作为一个Facebook应用程序,我有一个友好的建议。 既然你的代码正在工作,你应该考虑将它包装在它自己的命名空间中,并实现模块模式。这样做可以保证你的函数名,特别是load()不会在同一个FB页面上被其他应用程序冲突或被覆盖。 我创建了一个小的示例应用程序在这里。你可以像这样简单: if(!window.Carlin){window.Carling = {}; } Carlin.Locator = function(){ var map,markers,infoWindow,locationSelect; markers = []; 函数load(){} 函数searchLocations(){} 函数clearLocations(){} //...etc return { init:load } }(); $(document).ready(Carlin.Locator.init); I have used this tutorial from Google to build a web app that finds the closest store from the user entered location:http://code.google.com/apis/maps/articles/phpsqlsearch_v3.htmlI have my app almost working the way I want it, upon page load, the map is loaded, centered and set to zoom level 6 and the user fills out the form with their location.The app then pulls all the store info from the db and populates the map with a marker for each.The zoom level seems to decrease aswell but I can't find this in the code anywhere.What I actually want to do on submit is zoom in to zoom level 6 and center the map to the latitude and longitude of the user entered location and output info on the nearest stores, e.g the nearest 5. I was wondering if anyone here knew how to implement this feature?index.php<div> <input type="text" id="addressInput" size="50"/> <input type="hidden" id="radiusSelect" value="5"/> <input type="button" onclick="searchLocations()" value="Search"/></div><div><select id="locationSelect" style="width:100%;visibility:hidden"></select></div><div id="map" style="width:100%; height:50%"></div><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script><script type="text/javascript">//<![CDATA[var map;var markers = [];var infoWindow;var locationSelect;function load() { map = new google.maps.Map(document.getElementById("map"), { center: new google.maps.LatLng(54.600939134593, -2.399894114594), zoom: 6, mapTypeId: 'roadmap', mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU} }); infoWindow = new google.maps.InfoWindow(); locationSelect = document.getElementById("locationSelect"); locationSelect.onchange = function() { var markerNum = locationSelect.options[locationSelect.selectedIndex].value; if (markerNum != "none"){ google.maps.event.trigger(markers[markerNum], 'click'); } };}function searchLocations() { var address = document.getElementById("addressInput").value; var geocoder = new google.maps.Geocoder(); geocoder.geocode({address: address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { searchLocationsNear(results[0].geometry.location); } else { alert(address + ' not found'); } });}function clearLocations() { infoWindow.close(); for (var i = 0; i < markers.length; i++) { markers[i].setMap(null); } markers.length = 0; locationSelect.innerHTML = ""; var option = document.createElement("option"); option.value = "none"; option.innerHTML = "See all results:"; locationSelect.appendChild(option);}function searchLocationsNear(center) { clearLocations(); var radius = document.getElementById('radiusSelect').value; var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius; downloadUrl(searchUrl, function(data) { var xml = parseXml(data); var markerNodes = xml.documentElement.getElementsByTagName("marker"); var bounds = new google.maps.LatLngBounds(); for (var i = 0; i < markerNodes.length; i++) { var town = markerNodes[i].getAttribute("town"); var postcode = markerNodes[i].getAttribute("postcode"); var name = markerNodes[i].getAttribute("name"); var address = markerNodes[i].getAttribute("address"); var distance = parseFloat(markerNodes[i].getAttribute("distance")); var latlng = new google.maps.LatLng( parseFloat(markerNodes[i].getAttribute("lat")), parseFloat(markerNodes[i].getAttribute("lng"))); var id = markerNodes[i].getAttribute("id"); var fname = markerNodes[i].getAttribute("fname"); var link = '<a href="http://www.domain.co.uk/stores/' + fname + '-' + id + '.html" target="_blank" title="Store: ' + town + '">More info</a>'; createOption(name, distance, i); createMarker(latlng, name, address, town, postcode, link); bounds.extend(latlng); } map.fitBounds(bounds); locationSelect.style.visibility = "visible"; locationSelect.onchange = function() { var markerNum = locationSelect.options[locationSelect.selectedIndex].value; google.maps.event.trigger(markers[markerNum], 'click'); }; }); } function createMarker(latlng, name, address, town, postcode, link) { var html = "<b>" + town + "</b> <br/>" + address + "<br/>" + postcode + "<br/>" + link; var marker = new google.maps.Marker({ map: map, position: latlng }); google.maps.event.addListener(marker, 'click', function() { infoWindow.setContent(html); infoWindow.open(map, marker); }); markers.push(marker);} function createOption(name, distance, num) { var option = document.createElement("option"); option.value = num; option.innerHTML = name + "(" + distance.toFixed(1) + ")"; locationSelect.appendChild(option); } 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 parseXml(str) { if (window.ActiveXObject) { var doc = new ActiveXObject('Microsoft.XMLDOM'); doc.loadXML(str); return doc; } else if (window.DOMParser) { return (new DOMParser).parseFromString(str, 'text/xml'); } } function doNothing() {}//]]></script><script type="text/javascript"> $(document).ready(function() { load(); });</script>phpsqlsearch_genxml.php<?php$db_conn = mysql_connect('xxx.xxx.xx.xx', 'xxxxxxxx', 'xxxxxx') or die('error');mysql_select_db('uk_db', $db_conn) or die(mysql_error());// Get parameters from URL$center_lat = $_GET["lat"];$center_lng = $_GET["lng"];$radius = $_GET["radius"];if(!$_GET['zoom']) { $_GET['zoom'] = 11; }// Start XML file, create parent node$dom = new DOMDocument("1.0");$node = $dom->createElement("markers");$parnode = $dom->appendChild($node);// Select all the rows in the markers table$query = 'SELECT address1, address2, address3, longitude, latitude, name, town, store_id, postcode, storenumber FROM uk_store WHERE isActive=1 ';if($_GET["region"] != '') { $query .= ' AND region = "' . $_GET["region"] . '"';} else { $query .= ' AND region in("Scotland", "England", "Wales", "Northern Ireland") ';}// lets start to check what has been search onif($_GET['postcode'] != '') { //lets make sure postcode only has numbers letter and spaces $searchparams .= 'postcode=' . $_GET['postcode'] . '&amp;'; $postcode = $_GET['postcode']; $postcode = verifyInput($postcode); $query .= " AND postcode = '" . $postcode . "'";}if($_GET['town'] != '') { // make sure town only has letters or spaces. $searchparams .= 'town=' . $_GET['town'] . '&amp;'; $town = $_GET['town']; $town = verifyInput($town); $query .= " AND town = '" . $town . "'";}if($_GET['min_lat'] && $_GET['min_long'] && $_GET['max_lat'] && $_GET['max_long'] ) { $query .= " AND latitude BETWEEN " . $_GET['min_lat'] . " AND " . $_GET['max_lat'] . " AND longitude BETWEEN " . $_GET['min_long'] . " AND " . $_GET['max_long'] ; $mapsearch = 1;}if(!($_GET['postcodeLat'] && $_GET['postcodeLong'])) { $query .= " ORDER BY Region, Town , Name "; }$result = mysql_query($query);if (!$result) { die("Invalid query: " . mysql_error());}header("Content-type: text/xml");echo '<markers>';if($_GET['postcodeLat'] && $_GET['postcodeLong']){ $count = 0; // we need to sort the results by distance while ($row = @mysql_fetch_array($result, MYSQL_ASSOC)) { $address = $row['address1'] . ' ' . $row['address2'] . ' ' . $row['address3']; $distance = distance($_GET['postcodeLat'], $_GET['postcodeLong'], $row['latitude'], $row['longitude']); $row['distance'] = number_format($distance, 2); $row['fname'] = $row['town'] . '-' . $row['name']; $row['fname'] = str_replace("'",'', $row['fname']); $row['fname'] = ereg_replace(' ','-', $row['fname']); $row['fname'] = ereg_replace('\/','-', $row['fname']); $row['fname'] = ereg_replace('\(','', $row['fname']); $row['fname'] = ereg_replace('\)','', $row['fname']); $row['fname'] = strtolower($row['fname']); //get distance and add to $row array $results[$distance.$row['id']] = $row; } ksort($results); foreach ($results as $key => $row) { // ADD TO XML DOCUMENT NODE $address = $row['address1'] . ' ' . $row['address2'] . ' ' . $row['address3']; echo '<marker '; echo 'name="' . parseToXML($row['name']) . '" '; echo 'fname="' . parseToXML($row['fname']) . '" '; echo 'town="' . parseToXML($row['town']) . '" '; echo 'lat="' . $row['latitude'] . '" '; echo 'lng="' . $row['longitude'] . '" '; echo 'id="' . $row['store_id'] . '" '; echo 'address="' . $address . '" '; echo 'distance="' . $row['distance'] . '" '; echo 'postcode="' . $row['postcode'] . '" '; echo 'storenumber="' . $row['storenumber'] . '" '; echo 'address1="' . parsetoXml($row['address1']). '" '; echo 'address2="' . parsetoXml($row['address2']). '" '; echo 'address3="' . parsetoXml($row['address3']). '" '; echo '/>'; }}else{ // Iterate through the rows, printing XML nodes for each while ($row = @mysql_fetch_assoc($result)) { $address = $row['address1'] . ' ' . $row['address2'] . ' ' . $row['address3']; $row['fname'] = $row['town'] . '-' . $row['name']; $row['fname'] = ereg_replace(' ','-', $row['fname']); $row['fname'] = ereg_replace('\/','-', $row['fname']); $row['fname'] = ereg_replace('\(','', $row['fname']); $row['fname'] = ereg_replace('\)','', $row['fname']); // ADD TO XML DOCUMENT NODE echo '<marker '; echo 'name="' . parseToXML($row['name']) . '" '; echo 'fname="' . strtolower(parseToXML($row['fname'])) . '" '; echo 'town="' . parseToXML($row['town']) . '" '; echo 'lat="' . $row['latitude'] . '" '; echo 'lng="' . $row['longitude'] . '" '; echo 'id="' . $row['store_id'] . '" '; echo 'isSurg="' . $row['isLaserSurgery'] . '" '; echo 'isCons="' . $row['isLaserConsult'] . '" '; echo 'address="' . parsetoXml($address). '" '; echo 'address1="' . parsetoXml($row['address1']). '" '; echo 'address2="' . parsetoXml($row['address2']). '" '; echo 'address3="' . parsetoXml($row['address3']). '" '; echo 'postcode="' . $row['postcode'] . '" '; echo 'storenumber="' . $row['storenumber'] . '" '; echo '/>'; }}// End XML fileecho '</markers>';// make sure the data is xml friendlyfunction 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; }// calculate the distance in miles or kms between any two points function distance($lat1, $lon1, $lat2, $lon2, $unit = '') { $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; if($unit != '') { $unit = strtoupper($unit); }if ($unit == "K") { return ($miles * 1.609344); } else if ($unit == "N") { return ($miles * 0.8684);} else { return $miles; }} function VerifyInput ($input, $forceInt = false) { if (is_numeric($input)) { return $input; } elseif (!$forceInt) { if (get_magic_quotes_gpc() && trim(ini_get("magic_quotes_sybase")) == "") { $input = stripslashes($input); $input = str_replace("'", "", $input); $input = str_replace("`", "", $input); } elseif (!get_magic_quotes_gpc()) { $input = str_replace("'", "", $input); $input = str_replace("`", "", $input); } return $input; } elseif ($forceInt) { return 0; } } ?>Apologies, that's a lot of pasting there but I thought it better to include everything rather than risk someone not being able to answer because there wasn't enough detail.UPDATEI have tried inserting this piece of code into the searchLocations function but it doesn't seem tochange the behaviour in anyway:function searchLocations() { var address = document.getElementById("addressInput").value; var geocoder = new google.maps.Geocoder(); geocoder.geocode({address: address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { searchLocationsNear(results[0].geometry.location); /////////////// new code var myOptions = { zoom: 11, center: address.geometry.location, mapTypeId: google.maps.MapTypeId.TERRAIN } map = new google.maps.Map(document.getElementById("map"), myOptions); //////////////// } else { alert(address + ' not found'); } });} 解决方案 Since you said this would be used as a Facebook app, I have a friendly suggestion.Now that your code is working, you should look into wrapping it in its own namespace and implement the module pattern. Doing so will guarantee that your function names, especially load(), do not clash or get overwritten by other apps on the same FB page.I have created a small sample app here. Yours could be as simple as something like:if (!window.Carlin) { window.Carling = {}; }Carlin.Locator = function() { var map,markers,infoWindow,locationSelect; markers = []; function load() { } function searchLocations() { } function clearLocations() { } //...etc return { init: load }}();$(document).ready(Carlin.Locator.init); 这篇关于Google Maps API v3:如何设置缩放级别并将地图中心映射到用户提交的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 10:33