将地理编码的Google地图添加到div

时间:2012-12-18 07:45:59

标签: google-maps-api-3 geolocation

我花了一整天时间查看文档和示例,但我将自己弄清楚了。我希望我可以按照正确的方式指导我这样做。我正在使用jQuery。

目的是制作一张地图,向学生展示该国that a story所指的地方。我使用cut&paste solution实现了一次,但是当切换div时它不起作用 - 长话短说,我觉得我需要重做它,但有点超出我的深度。我找到了elsewhere on here地理编码代码:

var geocoder = new google.maps.Geocoder();
var address = $("#infopanel .map a.header").text();
map = $("#infopanel .map div");

geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    } 
});

这是添加地图的代码,但请注意我无法弄清楚如何将地理编码的结果导入mapOptions的中心变量:

var mapOptions = {
    center: new google.maps.LatLng(*geocoded-data*),
    zoom: 3,
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    panControl: false,
    zoomControl: true,
    mapTypeControl: false,
    scaleControl: false,
    streetViewControl: false,
    overviewMapControl: false
   };

    new google.maps.Map(map,mapOptions);

以下是来自this answer的带调整大小/中心解决方案的slideToggle代码,但同样,我如何将地理编码数据导入setCenter:

$("#infopanel ul li > div").slideToggle("fast"); // hide the content
$("#infopanel a.header").click(function(e){ // toggle the content.
var hascontent = $(this).next("div");
if (hascontent.length == 1) {
    e.preventDefault();
    $(this).next().slideToggle("slow", function () {
        google.maps.event.trigger(map, "resize"); // resize map
        map.setCenter(*geocoded-data*); // center map
        });
    }
});

对于上下文,这里是HTML所有的HTML:

<li class="map"><a href="" class="header">Zimbabwe</a>
    <div style="width:220px;height:220px;"><a href="http://maps.google.com.au/maps?q=Zimbabwe&amp;z=3">Find Zimbabwe on Google Maps</a></div>
</li>

如何连接这三者之间的点?

1 个答案:

答案 0 :(得分:0)

这是一个设置center of the map from a geocoded address的简单示例。

关键是:

  if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
      map.setCenter(results[0].geometry.location);

,如果地理编码操作成功,则将地图的中心设置为返回的值。

相关问题