I've created a small JavaScript code to geocode various locations and display them on a map. While I can successfully plot a single location, I'm struggling to get it working for multiple locations. Below is the code that currently works for one location only.
var geocoder = new google.maps.Geocoder();
var address = "Melbourne";
geocoder.geocode( { 'address': address}, function(results, status) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
initialize(latitude,longitude);
});
function initialize(latitude,longitude) {
var latlng1 = new google.maps.LatLng(latitude,longitude);
var myOptions = {
zoom: 2,
panControl: false,
zoomControl: false,
mapTypeControl: false,
streetViewControl: false,
center: latlng1,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
scrollwheel: false,
};
var map = new google.maps.Map(document.getElementById("google-container"),myOptions);
var marker = new google.maps.Marker({
position: latlng1,
map: map,
});
}
I attempted to add a second location with the code below, but it seems I missed something important. It's clear that I'm still learning JavaScript.
var geocoder = new google.maps.Geocoder();
var address = "Seoul";
var address2 = "Melbourne";
geocoder.geocode( { 'address': address}, function(results, status) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
initialize(latitude,longitude);
});
geocoder.geocode( { 'address': address2}, function(results, status) {
var latitude2 = results[0].geometry.location.lat();
var longitude2 = results[0].geometry.location.lng();
initialize(latitude2,longitude2);
});
function initialize(latitude,longitude) {
var latlng1 = new google.maps.LatLng(latitude,longitude);
var latlng2 = new google.maps.LatLng(latitude2,longitude2);
var myOptions = {
zoom: 2,
panControl: false,
zoomControl: false,
mapTypeControl: false,
streetViewControl: false,
center: latlng1,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
scrollwheel: false,
};
var map = new google.maps.Map(document.getElementById("google-container"),myOptions);
var marker = new google.maps.Marker({
position: latlng1,
map: map,
});
var marker2 = new google.maps.Marker({
position: latlng2,
map: map,
});
}
Any thoughts or suggestions would be greatly appreciated!