谷歌地图与magento,自定义地图

时间:2015-01-30 17:13:58

标签: jquery google-maps magento

我正在Magento的一个页面中制作一个简单的谷歌地图。

我在标题中引用了jQuery和Google地图。

到目前为止,我正在呈现以下代码:

<div id="my_map" style="height: 400px; width: 400px margin-bottom: 0px; border-radius: 10px; margin-top: 30px;">&nbsp;</div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">// <![CDATA[
jQuery(document).ready(function(){
        var options = {
            controls: {
                   panControl: false,
                   zoomControl: false,
                   mapTypeControl: false,
                   scaleControl: false,
                   streetViewControl: false,
                           navigationControl: false,
                   overviewMapControl: false
               },
            scrollwheel: false,
            maptype: 'TERRAIN',
            markers: [
                        {
                    latitude: 22.312895, 
                    longitude: 79.439376,
                    html: "Indien",
                    icon: {
                        iconsize: [20, 34],
                        shadowsize: [37, 34],
                        iconanchor: [9, 34],
                        shadowanchor: [19, 34]
                    }
                }
            ],
            latitude: 0.00000, 
            longitude: 0.000000,
            zoom: 2
        };
        jQuery("#my_map").gMap(options);
    });
// ]]></script>

这在Wordpress中没有任何问题,具有完全相同的引用。

加载页面时页面只是空白,但代码显示在源代码中(源代码中呈现的代码):

<div id="my_map" style="height: 400px; width: 400px margin-bottom: 0px; border-radius: 10px; margin-top: 30px;">&nbsp;</div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">// <![CDATA[
jQuery(document).ready(function(){
        var options = {
            controls: {
                   panControl: false,
                   zoomControl: false,
                   mapTypeControl: false,
                   scaleControl: false,
                   streetViewControl: false,
                           navigationControl: false,
                   overviewMapControl: false
               },
            scrollwheel: false,
            maptype: 'TERRAIN',
            markers: [
                        {
                    latitude: 22.312895, 
                    longitude: 79.439376,
                    html: "Indien",
                    icon: {
                        iconsize: [20, 34],
                        shadowsize: [37, 34],
                        iconanchor: [9, 34],
                        shadowanchor: [19, 34]
                    }
                }
            ],
            latitude: 0.00000, 
            longitude: 0.000000,
            zoom: 2
        };
        jQuery("#my_map").gMap(options);
    });
// ]]></script>

我的问题是,代码出了什么问题,因为显示空白页很简单?

我创建了一个JSFiddle Here - 这似乎也出现了同样的问题。

2 个答案:

答案 0 :(得分:1)

Magento主要使用prototype.js作为javascript,如果您想尝试,可以查看自定义Product locator

var ScandProductLocator = new Class.create();
ScandProductLocator.prototype = {
initialize : function(data){

if (!data) data = {};
// Own objects
    this.pre_radius = 0;

// Google objects
    this.map = null;
    this.geocoder = new google.maps.Geocoder();
    this.infowindow = new google.maps.InfoWindow();
    // Scand Ltd. position by default
    this.defaultLat = data.lat ? data.lat : 53.889713;
    this.defaultLng = data.lng ? data.lng : 27.536919;
    // count of unique products
    this.productCount = data.count ? data.count : 0;
    // list af addresses
    this.productAddresses = data.addresses ? data.addresses : {};
    // category to display by default
    this.defaultOption =  0;
    // arrays of positions to calculate center of map
    this.lats = [];
    this.lngs = [];
    // list of google.maps.Marker
    this.markers = [];
    // count of horizontal/vertical cells
    this.xCells = 13;
    this.yCells = 10;

    this.currentOption = null;

    this.validate();
},

validate : function () {
    if (this.productCount == 0)
        return;

    var lats = [],
        lngs = [];

    for (var opt_id in this.productAddresses) {
        if (this.productAddresses.hasOwnProperty(opt_id)) {
            this.productAddresses[opt_id].map(function(product){
                if (product.address && !product.lat && !product.lng) {
                    this.geocoder.geocode({'address': product.address.replace(/\<br\>/g, ", ")}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            var item = results.first();
                            product.lat = item.geometry.location.lat();
                            product.lng = item.geometry.location.lng();
                            lats.push(product.lat);
                            lngs.push(product.lng);
                            //this.addMarker(product);
                        }
                    });
                }
            }, this);
        }
    }
},

addProduct : function (opt_id, productsToShow) {
    this.productAddresses[opt_id].collect(function(product){
        if ((product.lat && product.lng) || (product.address !="")) {
            productsToShow[product.product_id] = product;
            this.lats.push(product.lat);
            this.lngs.push(product.lng);

        }
    }, this);
    return productsToShow;
},

showProductsByOption : function (opt_id, no_clear, no_resize) {
    var gridMarkers = {},
        productsToShow = {};
    this.currentOption = opt_id;

    if (!no_clear) {
        $$('#productlocator_categories li a').each(function(e){
            e.setStyle({fontWeight: e === $('cat_'+opt_id) ? 'bold' : 'normal'});
        });

        var i = 0;
        for (i; i < this.markers.length; i++) {
            this.markers[i].setMap(null);
        }

        this.markers = [];
        this.lats = [];
        this.lngs = [];
    }

    if (this.productCount == 0) {
        return;
    }
    else if (opt_id == 0) {
        for (var opt_id in this.productAddresses) {
            productsToShow = this.addProduct(opt_id, productsToShow);
        }
    }
    else if (this.productAddresses.hasOwnProperty(opt_id)) {
        productsToShow = this.addProduct(opt_id, productsToShow);
    }

    if(this.map.getBounds()) {
        var max_lat = this.map.getBounds().getNorthEast().lat(),
            min_lat = this.map.getBounds().getSouthWest().lat(),
            max_lng = this.map.getBounds().getNorthEast().lng(),
            min_lng = this.map.getBounds().getSouthWest().lng();
    }
    else {
        var min_lat = this.lats.min()-5, max_lat = this.lats.max()+5,
            min_lng = this.lngs.min()-5, max_lng = this.lngs.max()+5;
    }

    var lat_dim = (max_lat - min_lat) / this.xCells;
    var lng_dim = (max_lng - min_lng) / this.yCells;

    for (var ndx in productsToShow) {
        if (productsToShow.hasOwnProperty(ndx)) {
            var product = productsToShow[ndx];
            var cell_lng_ind = Math.ceil((product.lng - min_lng) / lng_dim);
            var cell_lat_ind = Math.ceil((product.lat - min_lat) / lat_dim);

            if (!gridMarkers[cell_lng_ind])
                gridMarkers[cell_lng_ind] = {};
            if (!gridMarkers[cell_lng_ind][cell_lat_ind])
                gridMarkers[cell_lng_ind][cell_lat_ind] = {};
            if (!gridMarkers[cell_lng_ind][cell_lat_ind]['products'])
                gridMarkers[cell_lng_ind][cell_lat_ind]['products'] = [];
            gridMarkers[cell_lng_ind][cell_lat_ind]['products'].push(product);
            //this.addMarker(product);
        }
    }

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

    for (var lngName in gridMarkers) {
        for (var latName in gridMarkers[lngName]) {
            var cellText = "",
                lat = 0,
                lng = 0,
                info = "";

            for (var i = 0; i < gridMarkers[lngName][latName]['products'].length; i++) {
                var product = gridMarkers[lngName][latName]['products'][i];
                lat += product.lat;
                lng += product.lng;
                info = '';
                if (product.address && product.address != '')
                    info += '<span class="addr">' + product.address + '</span>';
                if (product.phone && product.phone != '')
                    info += '<span class="phone">' + product.phone + '</span>';

                cellText += "<span class='product_title'>" + (product.product_url ? "<a href='"+product.product_url +"' target='_blank'>" : "");
                cellText +=  product['product_name'];
                cellText += "</span>" +  ((product.product_url)? "</a>":"");
                cellText += "<p class='product_description'>" + info + "</p>";
            }

            if (gridMarkers[lngName][latName]['products'].length > 0) {
                var marker = {
                    'category_name' :   gridMarkers[lngName][latName]['products'][0]['category_name'],
                    'product_id' :  gridMarkers[lngName][latName]['products'][0]['product_id'],
                    'product_name': gridMarkers[lngName][latName]['products'][0]['product_name'],
                    'lat': lat/gridMarkers[lngName][latName]['products'].length,
                    'lng': lng/gridMarkers[lngName][latName]['products'].length,
                    'info': cellText,
                    'items_count': gridMarkers[lngName][latName]['products'].length,
                    'category_lat': gridMarkers[lngName][latName]['products'][0]['category_lat'],
                    'category_long': gridMarkers[lngName][latName]['products'][0]['category_long']
                };
                this.addMarker(marker);
                bounds.extend(new google.maps.LatLng(marker.lat, marker.lng));




enter code here

    if(!bounds.isEmpty() && (no_resize === undefined || !no_resize)) {
        this.map.fitBounds(bounds);
    }       
},

addMarker : function (product) {
    if (!this.map) return;

    var marker = new google.maps.Marker(
        {
            position: new google.maps.LatLng(product.lat, product.lng),
            map: this.map,
            /*icon.size = new google.maps.Size(35, 35),
            icon.anchor = new google.maps.Point(0, 35),*/
            size : 80,
            title: (product.items_count < 2)? product.product_name : "" + product.items_count + " items",
            icon : 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+ product.product_id +'|0431B4|FFFFFF'       
        }
    );






        );


    var context = this;
    google.maps.event.addListener(marker, 'click', function() {
        var content = (product.items_count == 1)? product.info : "<p class='items_count'>" + product.items_count + " items</p>" + product.info;
        context.infowindow.setContent("<div class='infowindow'>" + content + "</div>");
        context.infowindow.open(context.map, marker);
    });



    var circle = new google.maps.Circle({
          map: this.map,
          radius: this.pre_radius,    // 10 miles in metres 16093
          fillColor: '#E6E6E6',
          fillOpacity: 0.0 ,
          strokeOpacity : 0.1,
          strokeWeight: 1,
          strokeWidth:1
        });
    circle.bindTo('center', marker_cat, 'position');        



    this.markers.push(marker);
    this.lats.push(product.lat);
    this.lngs.push(product.lng);

    this.markers.push(marker_cat);
    this.lats.push(product.category_lat);
    this.lngs.push(product.category_long);
},




draw : function () {
    var latlng = new google.maps.LatLng(this.defaultLat, this.defaultLng);
    disableDefaultUI:false;
    var map_options = {

            panControl:true,
            zoomControl:true,
            mapTypeControl:true,
            scaleControl:true,
            streetViewControl:true,
            overviewMapControl:true,
            rotateControl:true,     

      center: latlng,
      zoom: 180,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var circle = new google.maps.Circle({

          map: this.map,
          radius: 16093,    // 10 miles in metres 16093
          fillColor: '#AA0000'
        });
        circle.bindTo('center', map_options, 'position');


    this.map = new google.maps.Map(document.getElementById("map_canvas"), map_options);

    this.showProductsByOption(this.defaultOption);

    /* Add rebuild markers (regroup) on resize map */
    var context = this;
    google.maps.event.addListener(this.map, 'bounds_changed', function() {
        if(context.zoom !== this.getZoom()) {
            context.zoom = this.getZoom();
            context.showProductsByOption(context.currentOption, false, true);
        }
    });
},

changeCircle : function (radius) {
    /*Takes de radius from  function calcRadius(radio)*/



    this.pre_radius = radius;

}
}

你可以看到,在这种情况下,它的map_canvas和主要检查是否像函数一样,我希望这段代码可以帮助你

答案 1 :(得分:0)

要使用gMap插件,您必须在http://gmap.nurtext.de/js/jquery.gmap-1.1.0-min.js中包含它。

所以,有三个组件:

  1. Google地图库
  2. JQuery框架
  3. JQuery gMaps插件