使用 Google Maps JavaScript API v3 和 Geocoding API 映射多个位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29463131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mapping multiple locations with Google Maps JavaScript API v3 and Geocoding API
提问by lacoder
I'm using Google Maps JavaScript API v3 to generate a map with multiple locations/markers. I only have the address for these locations, not the coordinates, so I'm using the Geocoding API to get the coordinates.
我正在使用 Google Maps JavaScript API v3 生成具有多个位置/标记的地图。我只有这些位置的地址,没有坐标,所以我使用地理编码 API 来获取坐标。
I finally got Google's geocoding to work, so the location markers are showing up where they are supposed to be. However, the same contentis showing up in every InfoWindow. I seem to be unable to pass the location arrays into the geocode function. (Incidentally, I also tried creating a variable for the geocode results and moving the infoWindow function outsideof the geocode function, but I couldn't make that work either.)
我终于让谷歌的地理编码工作了,所以位置标记出现在他们应该在的地方。但是,每个 InfoWindow 中都显示相同的内容。我似乎无法将位置数组传递到地理编码函数中。(顺便说一句,我还尝试为地理编码结果创建一个变量并将 infoWindow 函数移到地理编码函数之外,但我也无法做到这一点。)
I've tried this a hundred different ways already. I hoping someone else will see what I haven't been able to see.
我已经尝试了一百种不同的方法。我希望其他人能看到我没能看到的东西。
var locations = [
['Location 1 Name', 'Location 1 Address', 'Location 1 URL'],
['Location 2 Name', 'Location 2 Address', 'Location 2 URL'],
['Location 3 Name', 'Location 3 Address', 'Location 3 URL']
];
geocoder = new google.maps.Geocoder();
for (i = 0; i < locations.length; i++) {
title = locations[i][0];
address = locations[i][1];
url = locations[i][2];
geocoder.geocode({ 'address' : locations[i][1] }, function(results, status) {
marker = new google.maps.Marker({
icon: 'marker_blue.png',
map: map,
position: results[0].geometry.location,
title: title,
animation: google.maps.Animation.DROP,
address: address,
url: url
})
infoWindow(marker, map, title, address, url);
})
}
function infoWindow(marker, map, title, address, url) {
google.maps.event.addListener(marker, 'click', function() {
var html = "<div><h3>" + title + "</h3><p>" + address + "<br></div><a href='" + url + "'>View location</a></p></div>";
iw = new google.maps.InfoWindow({ content : html, maxWidth : 350});
iw.open(map,marker);
});
}
回答by geocodezip
This is a duplicate of google map info window multiple addresses via xml, just not an exact duplicate. The geocoder is asynchronous, so when the geocoder callback runs, the value of address is that from the end of the loop for all the calls.
这是通过 xml复制的谷歌地图信息窗口多个地址,只是不完全重复。地理编码器是异步的,所以当地理编码器回调运行时,地址的值是所有调用的循环结束时的值。
The answer is the same: The simplest solution is to use function closure to associate the call to the geocoder with the returned result:
答案是一样的:最简单的解决方案是使用函数闭包将geocoder的调用与返回的结果关联起来:
function geocodeAddress(locations, i) {
var title = locations[i][0];
var address = locations[i][1];
var url = locations[i][2];
geocoder.geocode({
'address': locations[i][1]
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map,
position: results[0].geometry.location,
title: title,
animation: google.maps.Animation.DROP,
address: address,
url: url
})
infoWindow(marker, map, title, address, url);
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
} else {
alert("geocode of " + address + " failed:" + status);
}
});
}
code snippet:
代码片段:
var locations = [
['Location 1 Name', 'New York, NY', 'Location 1 URL'],
['Location 2 Name', 'Newark, NJ', 'Location 2 URL'],
['Location 3 Name', 'Philadelphia, PA', 'Location 3 URL']
];
var geocoder;
var map;
var bounds = new google.maps.LatLngBounds();
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
for (i = 0; i < locations.length; i++) {
geocodeAddress(locations, i);
}
}
google.maps.event.addDomListener(window, "load", initialize);
function geocodeAddress(locations, i) {
var title = locations[i][0];
var address = locations[i][1];
var url = locations[i][2];
geocoder.geocode({
'address': locations[i][1]
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map,
position: results[0].geometry.location,
title: title,
animation: google.maps.Animation.DROP,
address: address,
url: url
})
infoWindow(marker, map, title, address, url);
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
} else {
alert("geocode of " + address + " failed:" + status);
}
});
}
function infoWindow(marker, map, title, address, url) {
google.maps.event.addListener(marker, 'click', function() {
var html = "<div><h3>" + title + "</h3><p>" + address + "<br></div><a href='" + url + "'>View location</a></p></div>";
iw = new google.maps.InfoWindow({
content: html,
maxWidth: 350
});
iw.open(map, marker);
});
}
function createMarker(results) {
var marker = new google.maps.Marker({
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map,
position: results[0].geometry.location,
title: title,
animation: google.maps.Animation.DROP,
address: address,
url: url
})
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
infoWindow(marker, map, title, address, url);
return marker;
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>
回答by Preet
Step-1
第1步
First you have to create map location for that like, where do you want to add this map on your web app. So first create JSP/HTML/ASP page in which you have to create location where you want to display the map.
首先,您必须为此创建地图位置,例如您希望将此地图添加到 Web 应用程序的何处。因此,首先创建 JSP/HTML/ASP 页面,您必须在其中创建要显示地图的位置。
<div id="map_canvas" style="width: 1350px; height: 500px"></div>
Step-2
第2步
Below I write the script using which you can see the map on your web application.
下面我编写了脚本,您可以使用该脚本在 Web 应用程序上查看地图。
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=TRUEORFALSE"></script>
<script type="text/javascript">
var map;
var markers;
function initialize() {
$
.ajax({
type : "POST",
url : "Your Servlet Name", //Servlet Name
data : $("#FormID"),
success : function(responseJson) {
var result = $.parseJSON(responseJson);
markers = result;
// Below mapOptions var includes styling maps and zoom level of your map, it also includes mapTypeId.
var mapOptions = {
center : new google.maps.LatLng(
markers[0].latitude, markers[0].longitude),
zoom : 5,
scrollwheel: false,
styles : [ {
"featureType" : "administrative",
"elementType" : "labels.text.fill",
"stylers" : [ {
"color" : "#444444"
} ]
}, {
"featureType" : "landscape",
"elementType" : "all",
"stylers" : [ {
"color" : "#f2f2f2"
} ]
}, {
"featureType" : "poi",
"elementType" : "all",
"stylers" : [ {
"visibility" : "off"
} ]
}, {
"featureType" : "poi.park",
"elementType" : "geometry.fill",
"stylers" : [ {
"visibility" : "on"
}, {
"color" : "#1ba093"
} ]
}, {
"featureType" : "road",
"elementType" : "all",
"stylers" : [ {
"saturation" : -100
}, {
"lightness" : 45
} ]
}, {
"featureType" : "road.highway",
"elementType" : "all",
"stylers" : [ {
"visibility" : "simplified"
} ]
}, {
"featureType" : "road.arterial",
"elementType" : "labels.icon",
"stylers" : [ {
"visibility" : "off"
} ]
}, {
"featureType" : "transit",
"elementType" : "all",
"stylers" : [ {
"visibility" : "off"
} ]
}, {
"featureType" : "water",
"elementType" : "all",
"stylers" : [ {
"color" : "#00748c"
}, {
"visibility" : "on"
} ]
} ],
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document
.getElementById("map_canvas"), mapOptions);
addYourLocationButton(map,marker);
//Create and open InfoWindow.
var infoWindow = new google.maps.InfoWindow();
for (var i = 0; i < markers.length; i++) {
var data = markers[i];
var myLatlng = new google.maps.LatLng(
data.latitude, data.longitude);
var marker = new google.maps.Marker({
position : myLatlng,
animation: google.maps.Animation.DROP,
map : map,
title : //Any title that you want to display while cursor over the marker.
});
//Click event
(function(marker, data) {
google.maps.event
.addListener(
marker,
"click",
function(e) {
infoWindow
.setContent("<div style = 'width:300px;min-height:50px'>+Write information about your location if you want.+"</div>");
infoWindow
.open(map, marker);
});
})(marker, data);
}
}
});
}

