gpt4 book ai didi

php - 使用数组中的多个标记初始化谷歌地图

转载 作者:搜寻专家 更新时间:2023-10-31 22:12:17 25 4
gpt4 key购买 nike

我将 2 个数组传递给谷歌地图,一个用于位置(经过地理编码),另一个用于该位置的信息窗口。

有什么方法可以初始化 map 并一次绘制所有这些点,还是我必须创建第二个函数来绘制更多点?由于有多个点,我不确定除了绘制一个点,然后制作一个循环遍历数组并绘制其余部分的加法函数之外,还能怎么做。

这是代码。

这两个数组(我没有包含代码)是 $cityArray$title

function initialize() {
geocoder = new google.maps.Geocoder();
latlang = geocoder.geocode( { 'address':
'<?php echo json_encode($cityArray); ?>'},
function(results, status) {
//use latlang to enter city instead of coordinates
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click',
(function(marker, i) {
return function() {
infowindow.setContent(
'<?php echo json_encode($title); ?>'
);
infowindow.open(map, marker);
}
})(marker, i));
markersArray.push(marker);
}
else{
alert("Geocode was not successful for the following reason: "
+ status);
}
});
var myOptions = {
center: latlang, zoom: 4, mapTypeId: google.maps.MapTypeId.SATELLITE,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};

var gm = google.maps;
map = new google.maps.Map(document.getElementById("main_Content"),
myOptions);
plotMarkers();

} //end of initialization function

var infowindow = new google.maps.InfoWindow();

最佳答案

请引用我在上面使用的以下示例。

第 1 步:在您的页面标题中包含三个脚本文件,例如

(i). <scrip type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=Your_API_KEY"></script>
(ii).<scrip type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
(iii).<scrip type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>

第二步:页面脚本

<script type="text/javascript">

//initialize the map window

jQuery(document).ready(function () {
load();
});

jQuery(window).unload(function () {
GUnload();
});

var map;
var geocoder;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();

function load() {
if (GBrowserIsCompatible()) {
geocoder = new GClientGeocoder();
map = new GMap2(document.getElementById('map'));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
//map.setCenter(new GLatLng(35.048629,-0.820663), 4);
searchLocations();
document.getElementById('directions-panel').innerHTML = '';
var url_new = ''+ benObj.TEMPLATE_DIR +'/print.html';
var print_icon_url_new = '<a href="javascript:void(0);" class="print" onClick="window.open(\'' + url_new + '\');">Print</a><a href="#" class="link">Link</a>';
jQuery('#print_icon').html(print_icon_url_new);
}
}


//Search Locations with address input

function searchLocations() {

var address = document.getElementById('addressInput').value;
// alert(address);
var address_new = jQuery("#addressInput_new").val();
if (address_new != "Enter City or Zip") {
jQuery("#loc1").html(address_new);
}
geocoder.getLatLng(address, function (latlng) {
//alert(latlng);
if (!latlng) {
alert(address + ' not found');
} else {
searchLocationsNear(latlng);
}
});

}


// Search Near By Location to place the Markers and Information windows

function searchLocationsNear(center) {
var radius = document.getElementById('radiusSelect').value;
var searchUrl = ''+ benObj.BASE_ROOT +'/mapmarker?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&format=raw';


jQuery.get(searchUrl, function (data) {

var xml = GXml.parse(data);


var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();

var sidebar = document.getElementById('sidebar');
var sidebar_val = '';
//sidebar.innerHTML = 'Results Found';
jQuery("#sidebar").html(sidebar_val);

<!--jQuery("#loc_count").html(markers.length);-->


if (markers.length == 0) {
sidebar.innerHTML = 'No results found.';
map.setCenter(new GLatLng(35.048629, -0.820663), 4);
return;
}

var bounds = new GLatLngBounds();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute('name');
var address = markers[i].getAttribute('address');
var phone_new = markers[i].getAttribute('phonenumber');
var distance = parseFloat(markers[i].getAttribute('distance'));
var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
var markerchar = "b";
var marker = createMarker(point, name, address, phone_new);
map.addOverlay(marker);
// var location_count = jQuery('#loc_count').val();
jQuery('#loc_count').val(i + 1);

var sidebarEntry = createSidebarEntry(marker, name, address, distance, phone_new);

jQuery('#sidebar').append(sidebarEntry);


//sidebar.appendChild(sidebarEntry);

// ScrollPane.getContentPane().appendChild(sidebarEntry);
bounds.extend(point);

}
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
jQuery('#sidebar').jScrollPane();
//jQuery('#sidebar').reinitialise();

});

}

//To Create a Marker With Information Window

function createMarker(point, name, address, phone_new) {

var pinkIcon = new GIcon(G_DEFAULT_ICON);
pinkIcon.image = ""+ benObj.IMAGE_DIR +"addr-pin-1.png";
var markerOptions = {
icon: pinkIcon
};


var marker = new GMarker(point, markerOptions);
var event_calendar = "event_calendar";
var event_title = ""+ benObj.event_title +"";
var display = "block";
var e_dt_start = jQuery("#dtstart").val();
var e_dt_end = jQuery("#dtend").val();
var e_start_timestamp = (formatTimestring(e_dt_start));
var e_end_timestamp = (formatTimestring(e_dt_end));
var e_desc = jQuery("#edesc").val();
var StrippedString = e_desc.replace(/(<([^>]+)>)/ig, "");
var trimmed = StrippedString.replace(/^\s+|\s+$/g, '');
var html = '<b>' + name + '</b> <br/>' + address + '<br>contact: ' + phone_new + '<br><br><a href="javascript:void(0);" style="text-decoration:none;" onclick="addtocalender();" class="addtocal" id="add_to_cal">Add to Calendar<div class="summary" style="display:none;">' + event_title + ' - "' + name + '"</div><span class="dtstart date" title="' + e_dt_start + '" style="display:none;">8th Aug 2010</span><span class="dtend date" title="' + e_dt_end + '" style="display:none;">01:30am - 12:00pm</span><div class="event-desc" style="display:none;">' + trimmed + '</div><div class="event-locate" style="display:none;">' + name + ',' + address + '</div></a>&nbsp;|&nbsp;<a href="javascript:void(0);" style="text-decoration:none;">Remind Me</a><br><br>Get Direction From:<br><input type="hidden" id="start" value="' + address + '"><input type="text" id="end" value="" style="border: 1px solid #ECE6D5;">&nbsp;<input type="button" value="GO" onclick="calcRoute();" style="border: 1px solid #ECE6D5;padding-left:5px;">';
GEvent.addListener(marker, 'click', function () {
marker.openInfoWindowHtml(html);

//jQuery(this).addtocal();
});
return marker;
}

// To Make Sidebar Entry If need

function createSidebarEntry(marker, name, address, distance, phone_new) {
var div = document.createElement('div');
var html = '<div class="locrow clearfix"><div class="left" style="width:240px;"><span class="count" id="loc_count">' + jQuery("#loc_count").val() + '</span><address><strong>' + name + '</strong>' + address + '</address><span class="mapdate"><span class="icon date"></span>'+ benObj.event_start_month_date +' &ndash; '+ benObj.event_end_month_date_year +'</span></div><div class="right" style="width:154px;"><ul><li><span class="icon phone"></span>' + phone_new + '</li><li><span class="icon time"></span>11 am &ndash; 7 pm</li><li><span class="icon car"></span>distance ' + distance.toFixed(1) + ' mi</li></ul></div></div>';

div.innerHTML = html;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
GEvent.addDomListener(div, 'click', function () {
GEvent.trigger(marker, 'click');
});
GEvent.addDomListener(div, 'mouseover', function () {
div.style.backgroundColor = '#eee';
});
GEvent.addDomListener(div, 'mouseout', function () {
div.style.backgroundColor = '#fff';
});
return div;
}

// To make a Directions If need

function calcRoute() {
directionsDisplay = new google.maps.DirectionsRenderer();
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var url = "http://maps.google.co.in/maps?f=d&source=s_d&saddr=" + start + "&daddr=" + end + "&aq=0&vpsrc=0&hl=en&doflg=ptm&mra=ls&ie=UTF8&t=m&z=5&layer=c&pw=2";
var print_icon_url = '<a href="javascript:void(0);" class="print" onClick="window.open(\'' + url + '\');">Print</a><a href="#" class="link">Link</a>';

var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
directionsDisplay.setDirections(response);
jQuery('#print_icon').html(print_icon_url);
}
});
}

</script>

//为标记和信息窗口创建 XML

<?php
function mapMarker($center_lat,$center_lng,$radius)
{
$mysqli = $this->_getMySqlConnection();
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);

// Search the rows in the markers table
$query = sprintf("SELECT phone,street_address_1, store_name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < '%s' ORDER BY distance LIMIT 0 , 10",
$mysqli->real_escape_string($center_lat),
$mysqli->real_escape_string($center_lng),
$mysqli->real_escape_string($center_lat),
$mysqli->real_escape_string($radius));

$result = $mysqli->query($query);

header("Content-type: text/xml");
header('Access-Control-Allow-Origin: *');

$avoid_duplicate="";
// Iterate through the rows, adding XML nodes for each
while ($row = @$result->fetch_assoc())
{
if($avoid_duplicate!=$row['store_name'])
{
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['store_name']);
$newnode->setAttribute("address", $row['street_address_1']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
$newnode->setAttribute("phonenumber", $row['phone']);
$avoid_duplicate=$row['store_name'];
}
}

$outXML=$dom->saveXML();
$result->close();
$mysqli->close();
return $outXML;
}
?>

HTML 部分:

<div class="mapleft">
<div class="ScrollPane scroll-pane" id="sidebar" style="overflow: auto; height: 430px;"></div>
<div class="mapshadow"></div>
</div>
<input type="hidden" id="addressInput" value="<?php echo $zip_code;?>" />
<input type="hidden" id="radiusSelect" value="50" />
<input type="hidden" id="addressInput_temp" value="<?php echo $zip_code;?>" />
<input type="hidden" id="radiusSelect_temp" value="50" />
<input type="hidden" name="X_REQUESTED_WITH" value="XMLHttpRequest" />
<div class="mapright">
<div id="map" style="width: 475px; height: 450px"></div>
</div>
<div class="map-dir" id="directions-panel" style="float:right;width:488px;"></div>
<input type="hidden" id="loc_count" value="1" />

这些是会产生伟大结果的东西。

关于php - 使用数组中的多个标记初始化谷歌地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com