Display multiple google map list - google-maps

I am trying to display a list of agency with information such as phone, email etc...and for each a small google map with address. The address is dynamics and render through a loop in twig.
The problem is only the first map is render.
function initMap() {
var x = document.querySelectorAll('div[id^="map-"]');
for(var i = 1; i < x.length; ++i )
{
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(53.3496, -6.3263);
var mapOptions =
{
zoom: 16,
center: latlng
}
var stringAddress = '';
var stringAddress = $("#address-"+i).text();
map = new google.maps.Map(document.getElementById('map-'+ i), mapOptions);
codeAddress(stringAddress);//call the function
}
}
and my code function :
function codeAddress(address) {
geocoder.geocode( {address:address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);//center the map over the result
//place a marker at the 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);
}
});
}

I find the solution the loop was wrong.
instead of
for(var i = 1; i < x.length; ++i )
do
for(var i = 1; i <= x.length; ++i )

Related

Google Maps JavaScript API v3 Distance Matrix send lat and lng but return address

every one.
you can see this link.
Google.
this link show parameter variable origin1 and variable destinationB is mean lat and lng.
but i click calculate distances return there address.
i want lat and lng result.
how can?
i need help.
thank you friends.
The response of the DistanceMatrixService doesn't contain LatLng's.
When you take a look at the code you'll see that the LatLng's(used to draw the markers) will be requested via geocoding.
Of course you would be able to use the hardcoded LatLng's, but the result may differ, because the locations returned by the DistanceMatrixService must not be equal to these values.
How to get LatLng's regardless of the input-type(address or LatLng)?
The geocoding runs asynchronously, there is no guarantee that the results will return in a specific order. Therefore it's not possible to create a string like the demo does.
Instead create DOMNodes(where you want to display the LatLng's), pass these nodes as argument to addMarker , and in the geocode-callback set the content of the node to the desired value
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin1 = new google.maps.LatLng(55.930, -3.118);
var origin2 = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var destinationB = new google.maps.LatLng(50.087, 14.421);
var destinationIcon = 'http://www.google.com/mapfiles/dd-end.png';
var originIcon = 'http://www.google.com/mapfiles/dd-start.png';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 10
};
map = new google.maps.Map(document.getElementById('map-canvas'), opts);
geocoder = new google.maps.Geocoder();
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
//create a new "row"
var row=outputDiv.appendChild(document.createElement('div'));
var results = response.rows[i].elements;
//origin-marker
addMarker(origins[i], false,row.appendChild(document.createElement('code')));
//a list for the destinations
var list=row.appendChild(document.createElement('ul'));
for (var j = 0; j < results.length; j++) {
var item=list.appendChild(document.createElement('li'));
item.appendChild(document.createTextNode(' to '));
//destination-marker
addMarker(destinations[j], true,item.appendChild(document.createElement('code')));
item.appendChild(document.createTextNode([': ',
results[j].distance.text,
' in ',
results[j].duration.text
].join('')));
}
}
}
}
function addMarker(location, isDestination,node) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
node.appendChild(document.createTextNode('('+marker.getPosition().toUrlValue()+')'));
node.setAttribute('title',location);
node.style.background=(isDestination)?'red':'green';
google.maps.event.addDomListener(node,'click',function(){map.panTo(marker.getPosition())})
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
width: 50%;
}
#content-pane {
float:right;
width:48%;
padding-left: 2%;
}
#outputDiv>div:nth-child(n+2){
border-top:1px dotted silver;
}
#outputDiv code{
cursor:pointer;
color:#fff;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3&.js"></script>
<div id="content-pane">
<button type="button" onclick="calculateDistances();">
Calculate distances
</button>
<div id="outputDiv"></div>
</div>
<div id="map-canvas"></div>

Issue with google map API

I have to translate a google map api code from v2 to v3. I've tried but it is not working.
This is the old version code:
function getQueryVariable(variable){
var query = window.location.search.substring(1);
var vars=query.split("&");
for(var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
var map = null;
var geocoder = null;
function showAddress(address, year1,year2,year3) {
map = new GMap2(document.getElementById("map_canvas"));
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.getLatLng(address,function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 11);
var marker = new GMarker(point);
map.addOverlay(marker);
}
}
);
}
}
This is what I wrote:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(decodeURIComponent(pair[0]) {
return pair[1];
}
}
}
var map = null;
var geocoder = null;
function showAddress(address) {
var map=new google.maps.Map(document.getElementById("map_canvas"));
geocoder = new google.maps.Geocoder();
geocoder.geocode(address, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var center = results[0].geometry.location;
map.setCenter(center);
var marker = new google.maps.Marker({
map: map,
position: center
});
}
}
}
Someone can tell me what I'm doing wrong?
Thanks a lot.
Marcello
There are syntax errors in your code. But the main issue is you need to initialize the google.maps.Map object. Currently there are 3 required options in the google.maps.MapOptions object:
https://developers.google.com/maps/documentation/javascript/reference#MapOptions
center | LatLng | The initial Map center. Required.
mapTypeId | MapTypeId | The initial Map mapTypeId. Required.
zoom | number | The initial Map zoom level. Required.
This works for me:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(decodeURIComponent(pair[0])) {
return pair[1];
}
}
}
var map = null;
var geocoder = null;
function showAddress(address) {
var map=new google.maps.Map(document.getElementById("map_canvas"),{center:new google.maps.LatLng(0,0), zoom:2, mapTypeId : google.maps.MapTypeId.ROADMAP});
geocoder = new google.maps.Geocoder();
geocoder.geocode({address:address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var center = results[0].geometry.location;
map.setCenter(center);
if (results[0].geometry.viewport) map.fitBounds(results[0].geometry.viewport)
else if (results[0].geometry.bounds) map.fitBounds(results[0].geometry.bounds)
var marker = new google.maps.Marker({
map: map,
position: center
});
} else alert("Geocoder returns: " + status);
});
}
working example

google api to search nearby address using their latitude,longitude from database

I need to retrieve a set of nearby addresses from google api using their latitude,longitude values.Latitude,longitude values are retrieved from a database.Is there a way to accomplish this?
Use Google Maps Javascript Api.
https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
And Read a developer guide https://developers.google.com/maps/documentation/javascript/tutorial
Here is how it can be done with a combination of jquery and the google api. the $.getJSON call is invoking a service that gets a list of lat/lng objects in a pretty standard name and address kind of format and pushes everything into a marker array.
In this example the user enters an address in the "useradd" control, which becomes one blue marker, and some nearby things in the database are displayed as red markers.
I have found the map to be very sensitive to styling changes, especially modifying it's height and width, I am sure there is some way to deal with that, just have not found it yet.
<script type="text/javascript">
var geocoder;
var map;
var markersArray = [];
//---------------------------------------------------------------------------------------------------------------
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(0, 0); //add some real starting coords
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
$('#loadMsg').hide().ajaxStart(function () { $(this).show(); }).ajaxStop(function () { $(this).hide(); });
}
//---------------------------------------------------------------------------------------------------------------
function getStringfromJSON(invalue) {
if (!invalue) { return ''; } else { return invalue; }
}
function codeAddress() {
var address = document.getElementById("useradd").value;
if (address.length == 0) return;
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
geocoder.geocode
(
{ 'address': address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var blueIcon = new google.maps.MarkerImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png");
var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, icon: blueIcon, clickable: false });
marker.setTitle(address);
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var dist = document.getElementById("selMiles").value;
var pageurl = '../Search/GetNearbys?lat=' + lat + '&lng=' + lng + '&dist=' + dist;
$.getJSON(pageurl,
function (data) {
for (var x = 0; x < data.length; x++) {
var facid = data[x].ID;
var facname = getStringfromJSON(data[x].Name);
var streetaddress = getStringfromJSON(data[x].StreetAddress);
var address2 = getStringfromJSON(data[x].Address2);
var city = getStringfromJSON(data[x].City);
var state = getStringfromJSON(data[x].State);
var zip = getStringfromJSON(data[x].ZipCode);
var xlat = data[x].Latitude;
var xlng = data[x].Longitude;
var xlatlng = new google.maps.LatLng(xlat, xlng);
var xmarker = new google.maps.Marker({ map: map, position: xlatlng, facilityid: facid });
xmarker.setTitle(facname + ' ' + streetaddress + ' ' + address2 + ' ' + city + ',' + state + ' ' + zip);
markersArray.push(xmarker);
google.maps.event.addListener(xmarker, 'click',
function () {
window.open('../Profile?id=' + this.facilityid, '_blank');
});
}
},
function (succeess) { }
);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
markersArray.push(marker); //put it here so it gets reset after each search
}
);
}
</script>

Google Maps Api V3 Zoom links in infowindow not working

I am building a store locator using php sql and javascript. I've done this tutorial https://developers.google.com/maps/articles/phpsqlsearch_v3 and got it working. I am trying to implement zoom in/out links on the infoWindows, for when the user clicks a marker. Its not working, in FireFox I am getting no errors in the console. In Chrome I am getting Uncaught TypeError: Object # has no method 'setCenter'
Ive been searching the forums but have been unable to find a solution. Sorry I dont have a version online to look at, working locally. Below is the script I am using.
var map = null;
var markers = [];
var infoWindow;
var locationSelect;
//On page load Create a google map in #map
//Set default cordinates & Map style to roadmap
function load() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(43.907787,-79.359741),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
infoWindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50)
});
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none") {
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
//Search for LAT/LNG of a place using its address using Google Maps Geocoder
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
//Clears Prve location, in info box
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
}
//Look for locations near by and loop through all data getting lat & lng of each marker
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'http://localhost:8888/starward/wp-content/themes/starward/map_request.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var zoom = 18;
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address,zoom);
bounds.extend(latlng);
}
map.fitBounds(bounds);
map.setZoom(11);
// map.setCenter(center);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
//Creates marker on the map
//Adds event for user when they click address info pops up
function createMarker(latlng, name, address, zoom) {
//var html = "<b>" + name + "</b> <br/>" + address
// add the zoom links
var html = "<b>" + name + "</b> <br/>" + address
html += '<br>Zoom To';
html += ' [+]';
html += ' [-]';
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
marker.MyZoom = zoom;
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
locationSelect.appendChild(option);
}
//Look up XML sheet to get data
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
It works for me in both IE and Firefox. Although to me the behavior makes more sense if I set the center for the "ZoomTo" link as well:
html += '<br>Zoom To';

Google Maps markers show same info

I know that similar questions have been asked before but the provided answers don't solve my problem. I have a loop in which I iterate through places, create markers and add eventlisteners. When I click on any of the markers afterwards they all show the same information.
var geocoder;
var map;
function initialize() {
// Load places from xml file
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","person_city_clause.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var text =
xmlDoc.getElementsByTagName("text");
var places = [];
var descriptions = [];
for (var i=3; i<text.length; i++)
{
places.push(text[i].childNodes[0].nodeValue); // place
descriptions[places[i]] = descriptions.push(text[i-2].childNodes[0].nodeValue); // person
i=i+3;
}
// Create inital Google Map
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// fill map with place markers
geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var marker = [];
for (var i=0; i<places.length; i++)
{
geocoder.geocode( { 'address': places[i]}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
marker[i] = new google.maps.Marker({
map: map,
position: results[0].geometry.location});
listenMarker(marker[i], results[0].formatted_address );
}
})
}
function listenMarker(marker, place)
{
google.maps.event.addListener(marker, 'click', function(){
infowindow.setContent("" + place);
infowindow.open(map, this);});
}
}
edit: when I do alert(i) after geocoder.geocode I always get 32 (the size of the places array).
You need an array for the infowindows aswell, if you do not do this the infowindow variable gets overridden by the next marker..
The content is the same for all of them..
EDIT: Just make another global array:
var locations = [];
..code blabla
if(status == google.maps.GeocoderStatus.OK)
{
for(int k = 0; k<results.length;k++{
locations.push = results[k].geometry.location;
}
}
You can loop through this array using this:
for(int i=0; i<locations.length;i++)
{
}
Try setting a local var in the context of the function, that creates the event function:
...
var index = i;
if (status == google.maps.GeocoderStatus.OK) {
...
infowindow.setContent("" + index);