我有一个magento网站,我的产品就是业务。我想在产品页面上添加一个谷歌地图,需要有人帮我写代码。
我可以通过键入来调用邮政编码
<?php echo $_product->getpostcode() ?>
我已经从互联网上获取了代码,并试图将其整合到我的网站上。这是代码:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var geocoder;
var map;
var address = '<?php echo $_product->getpostcode() ?>'
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
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 id="map_canvas" style="width: 500px; height: 300px"></div>
目前,它正在代码中使用lat-long。如何将其更改为使用邮政编码?`
地图始终使用坐标。这就是地图的工作原理。如果您想使用邮政编码,您需要将其转换为坐标—该过程称为地理编码。
您的代码中有一个地理编码函数,它目前不起作用,因为您没有一个名为address
的元素,但它可以在使用时稍作调整。
您目前有一个名为address
的全局变量,其中包含您的邮政编码,所以让您的地理编码函数使用它:
在函数initialize()
的底部,添加对地理编码器函数的调用,并将全局变量传递给它
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
codeAddress(address);
}
更改该函数以接受参数:
function codeAddress(addy) {
然后使用它:
// var address = document.getElementById('address').value;
// The above line needs to be removed; the one below amended
geocoder.geocode( { 'address': addy}, function(results, status) {
//i have working function use it.
function initialize() {
var address = "<?php echo $address?>";
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(50.317408,11.12915);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("location-canvas"), myOptions);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{ content: '<b>'+address+'</b>',
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
} else {
alert("Address Not found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}