Google Map One Infobox Open - javascript

I am building a directory, in this example it's a directory for doctors. I created a javascript array called "locations". The visitor can check checkboxes on the map to choose which kind of doctor should be displayed.
This is a sample of the array of locations to loop through in a for loop
var locations = [
[0, 'Total Care', 1, 0, 0, 0, 0, 0, 'Lake Elsinore', '92530', 'CA', 33.6603, -117.3830, '(951) 674-8779', 1],
... etc
];
This explains each key
locations[i][0] = business claimed or not (0 = unclaimed and 1 is claimed)
locations[i][1] = name
locations[i][2] = if general practitioner = 1, else = 0
locations[i][3] = if surgeon = 1, else = 0
locations[i][4] = if cardiologist = 1, else = 0
locations[i][5] = if urologist = 1, else = 0
locations[i][6] = if gynecologist = 1, else = 0
locations[i][7] = if pulmonologist = 1, else = 0
locations[i][8] = city
locations[i][9] = zip code
locations[i][10] = state
locations[i][11] = latitude
locations[i][12] = longitude
locations[i][13] = phone number
locations[i][14] = z-index
All works fine. I have a search function so the visitor can search by name. In the google map code below, I want to find a way to have the infoBox open on the marker of the doctor that was entered in the search function e.g.
if (locations[i][1] == "doctor name"){
code here }
I have been trying to find a solution for the past three days and can't find it, so I would really appreciate some help. This is the Google Map code:
var infoBox = null;
function initialize()
{
var centerMap = new google.maps.LatLng(33.6603, -117.3830);
var mapOptions = {zoom: 11,center: centerMap,mapTypeId: google.maps.MapTypeId.ROADMAP}
var map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
setMarkers(map, locations);
}
function setMarkers(map, markers)
{
var image = {url: 'images/marker.png',size: new google.maps.Size(17, 23),origin: new google.maps.Point(0,0),anchor: new google.maps.Point(8, 23)};
gpr = $('#check1').is(':checked') ? 1 : 0; // general practitioner
srg = $('#check2').is(':checked') ? 1 : 0; // surgeon
car = $('#check3').is(':checked') ? 1 : 0; // cardiologist
uro = $('#check4').is(':checked') ? 1 : 0; // urologist
gyn = $('#check5').is(':checked') ? 1 : 0; // gynecologist
pul = $('#check6').is(':checked') ? 1 : 0; // pulmonologist
for (var i = 0; i < markers.length; i ++)
{
var locations = markers[i];
var siteLatLng = new google.maps.LatLng(locations[11], locations[12]);
var boxText = document.createElement('div');
boxText.style.cssText = 'some styling';
link = locations[1].replace(' ','_');
link = link.toLowerCase();
// find out if this genre of doctor was searched for
setMarker = 0;
if (gpr == 1){if (locations[2] == 1){setMarker = 1;}}
if (srg == 1){if (locations[3] == 1){setMarker = 1;}}
if (car == 1){if (locations[4] == 1){setMarker = 1;}}
if (uro == 1){if (locations[5] == 1){setMarker = 1;}}
if (gyn == 1){if (locations[6] == 1){setMarker = 1;}}
if (pul == 1){if (locations[7] == 1){setMarker = 1;}}
// if one of the checkboxes was checked
if (setMarker == 1)
{
if (locations[0])
{
boxText.innerHTML = 'some html with link'; // claimed business
}
else
{
boxText.innerHTML = 'some html without link'; // unclaimed business
}
var infoBoxOptions = {content: boxText,disableAutoPan: false,maxWidth: 0,pixelOffset: new google.maps.Size(5, -80),zIndex: locations[14],boxStyle: {background: "url('images/tip.png') no-repeat",opacity: 0.9,width: "405px",height: "75px",border: '0px solid #900'},closeBoxMargin: "13px 5px 5px 5px",closeBoxURL: "images/close.gif",infoBoxClearance: new google.maps.Size(1, 1),isHidden: false,pane: "floatPane",enableEventPropagation: false};
var marker = new google.maps.Marker({position: siteLatLng,map: map,title: locations[1],zIndex: locations[14],icon: image,html: boxText});
google.maps.event.addListener(marker, 'click', function (e) {infoBox.setContent(this.html);infoBox.open(map, this);});
var infoBox = new InfoBox(infoBoxOptions);
}
}
}
Your help will be much appreciated. Thank you.

Unless I'm misunderstanding, you can just loop through your markers until the title matches the search text, and then open the appropriate info box on that marker. Something like:
$('#searchButton').click(function() {
var searchText = $('#searchBox').val();
for (var i = 0; i < markers.length; i++) {
if (markers[i].title.indexOf(searchText) > -1)
infoBoxes[i].open(map, markers[i]);
}
});
This example assumes you have two existing parallel arrays of markers and their corresponding info boxes.

Related

How to get all the pins/markers in on click of a markercluster in google maps?

I am using google maps api to create a store locator with clusters and I am referring the marker cluster api.
I wanted to get the list of stores with in a markercluster rather than returning marker cluster with pins/markers. Please find the below code -
google.maps.event.addListener(mapsCore.mapsVar.markerCluster, 'clusterclick', function(cluster) {
var content = "";
// Convert lat/long from cluster object to a usable MVCObject
var info = new google.maps.MVCObject;
info.set('position', cluster.center_);
//----
//Get markers
console.log(cluster.getSize());
var markers = cluster.getMarkers();
var x = {};
$(mapsCore.mapsVar.totalResults.Result).each(function(k, v) {
$(markers).each(function(km, vm) {
if (parseFloat(v.LAT) == parseFloat(markers[km].position.lat()) && parseFloat(v.LON) == parseFloat(markers[km].position.lng())) {
// locArr[k] = { lat: parseFloat(v.CounterLatitude), lng: parseFloat(v.CounterLongitude) };
x.Counter_ID = v.Counter_ID;
x.Counter_Name = v.Counter_Name;
x.Counter_Zip_code = v.Counter_Zip_code;
x.Address_1 = v.Address_1;
x.Address_2 = v.Address_2;
x.Province = v.Province;
x.City = v.City;
x.Area = v.Area;
x.SubArea = v.SubArea;
x.Counter_Tel = v.Counter_Tel;
x.Counter_Email = v.Counter_Email;
x.Open_Time = v.Open_Time;
x.Close_Time = v.Close_Time;
x.LAT = v.LAT;
x.LON = v.LON;
x.MR_FLG = v.MR_FLG;
mapsCore.mapsVar.clusterDetail.Results.push(x);
x = {};
}
});
});
});
As a workaround you can set a custom image to an transparent png and text size to 0, that way it'll be invisible on the map.
cluster.setStyles({
url: your_path/transparent.png,
height: 20,
width: 20,
textSize: 0
});
Alternatively you can try and see if setting the image height and width to 0 works.
All,
thanks for your help for formatting my code and comments any way I found the solution for it. I will attach the spinet of code below
google.maps.event.addListener(mapsCore.mapsVar.markerCluster, 'clusterclick', function(cluster) {
var content = '';
// Convert lat/long from cluster object to a usable MVCObject
var info = new google.maps.MVCObject;
info.set('position', cluster.center_);
//----
//Get markers
console.log(cluster.getSize());
var markers = cluster.getMarkers();
var x = {};
mapsCore.mapsVar.clusterDetail.Counters.length = 0;
$(mapsCore.mapsVar.totalResults.Counters).each(function(k, v) {
$(markers).each(function(km, vm) {
console.log(parseFloat(v.CounterLatitude) == parseFloat(vm.position.lat()) && parseFloat(v.CounterLongitude) == parseFloat(vm.position.lng()));
if (parseFloat(v.CounterLatitude) == parseFloat(vm.position.lat())) {
// locArr[k] = { lat: parseFloat(v.CounterLatitude), lng: parseFloat(v.CounterLongitude) };
x.CounterCode = v.CounterCode;
x.CounterName = v.CounterName;
x.CounterZipCode = v.CounterZipCode;
x.AddressLine1 = v.AddressLine1;
x.AddressLine2 = v.AddressLine2;
x.Province = v.Province;
x.City = v.City;
x.Area = v.Area;
x.SubArea = v.SubArea;
x.CounterPhoneNumber = v.CounterPhoneNumber;
x.CounterEmailAddress = v.CounterEmailAddress;
x.CounterOpenTime = v.CounterOpenTime;
x.CounterCloseTime = v.CounterCloseTime;
x.CounterLatitude = v.CounterLatitude;
x.CounterLongitude = v.CounterLongitude;
x.IsMagicRingAvailable = v.IsMagicRingAvailable;
mapsCore.mapsVar.clusterDetail.Counters.push(x);
x = {};
}
});
});
console.log(mapsCore.mapsVar.clusterDetail);
var template = $.templates("#mapslist");
var output = template.render(mapsCore.mapsVar.clusterDetail);
$(".store-list-section").html(output);
});
Always need to reset the array of object like -
mapsCore.mapsVar.clusterDetail.Counters.length = 0;

Js Array detect: number of values from php array found (grabbed from database)

This is (again) about array (in my Google map project). After being voteddown, finally I succeed to show multiple markers based on Db data.
I have two PHP pages:
1. inc.php
2. index.php
In inc.php contains values in php array, as follow:
//...... previous code
$googlemap=$result['googlemap'];
$map[] = $googlemap;
}
echo implode(', ' , $map);
The result shows: -5.364000343425874,-150.364000343425874-5.362878747789552,-150.3640003436345874 (this line contains 2 values for example)
To get the values, I use native Ajax:
In index.php contains Javascript codes to fetch the php array (inc.php), extract them into each values for latt and long value, as follow:
Array Values from inc.php is caught by this code:
var wwwsitus = document.querySelector("#valdata").value;
The value inside #valdata grabbed by native ajax:
<script>
function strQuery(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("valdata").value = xmlhttp.responseText;
script_dkill()
}
}
xmlhttp.open("POST", "inc.php?q="+str, true);
xmlhttp.send(null);
}
//start: calling maps
function script_dkill() {
// --- some codes ---
//..........
//}
</script>
Extract #valdata:
var n_result = wwwsitus.split(',');
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];
Show the map from this format array:
var wwwsitus = [
['<h4>Universitas Lampung</h4>', x0,y0],
['<h4>Universitas Lampung</h4>', x1,y1]
];
All works 100%.
The problem is:
Values grabbed from database can be 1, 2 or more. (here, I limit the values into 5).
Question:
How do I detect the values in #valdata if #valdata contains 1 or more values so that I can create if for the result???. or, you have other suggestion to handle this.
I hope my question is very clear and pls help me out from this. Thnks.
UPDATED:
What I expect is, for instance:
var wwwsitus = document.querySelector("#valdata").value;
var n_result = wwwsitus.split(',');
if (wwwsitus =null) {
alert('No rent-house found near the place'); // if no value.
// no action
}
else if (wwwsitus =1) {
alert('Found 1 rent-houses'); // if found only 1 value
//continue to show the map based on the value - will show 1 marker.
var x0 = n_result[0];
var y0 = n_result[1];
var wwwsitus = [['<h4>Kost 1</h4>', x0,y0]];
}
else if (wwwsitus =2) {
alert('Found 2 rent-houses'); //if found 2 value
// continue to show the value - will show 2 markers.
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];
var wwwsitus = [['<h4>Kost 1</h4>', x0,y0],['<h4>Kost 2</h4>', x1,y1]];
}
HOWEVER, the alert() NOT SHOWING the real number of the values as in the Database. How should I code with this.?
This following solution perhaps stupid coding. But it finally works 1000%.
To detect number of values inside #valdata, I add one input field as follow:
<input type='hidden' id='numvalue' value=''/>
Create native Ajax again to grabbed the information about number of values in new file (e.g. num_inc.php)
Here, with that ajax, I will be able to get number of values exist based on mysql query and send to input field #numvalue.
Here's in num_inc.php last code:
$result = $uQuery->fetchColumn();
if($result> 0) {
echo $result; // number of value detected!!!
}
From the process, I finally can extract the data from #valdata and display the map successfully.
Here's the full code:
<script>
//document.getElementById("qfront").addEventListener("keydown", CalmDown, false);
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var datafound = document.getElementById("numvalue").value;
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
document.getElementById("valdata").value = xmlhttp2.responseText;
var wwwsitus = document.getElementById("valdata").value;
var n_result = wwwsitus.split(',');
if (datafound == 1) {
var x0 = n_result[0];
var y0 = n_result[1];
var wwwsitus = [
['<h4></h4>', x0,y0]
];
}
else if (datafound == 2) {
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];
var wwwsitus = [
['<h4></h4>', x0,y0],
['<h4></h4>', x1,y1]
];
}
else if (datafound == 3) {
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];
var x2 = n_result[4];
var y2 = n_result[5];
var wwwsitus = [
['<h4></h4>', x0,y0],
['<h4></h4>', x1,y1],
['<h4></h4>', x2,y2]
];
}
else if (datafound == 4) {
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];
var x2 = n_result[4];
var y2 = n_result[5];
var x3 = n_result[6];
var y3 = n_result[7];
var wwwsitus = [
['<h4></h4>', x0,y0],
['<h4></h4>', x1,y1],
['<h4></h4>', x2,y2],
['<h4></h4>', x3,y3]
];
}
else if (datafound == 5) {
var x0 = n_result[0];
var y0 = n_result[1];
var x1 = n_result[2];
var y1 = n_result[3];
var x2 = n_result[4];
var y2 = n_result[5];
var x3 = n_result[6];
var y3 = n_result[7];
var x4 = n_result[8];
var y4 = n_result[9];
var wwwsitus = [
['<h4></h4>', x0,y0],
['<h4></h4>', x1,y1],
['<h4></h4>', x2,y2],
['<h4></h4>', x3,y3],
['<h4></h4>', x4,y4]
];
}
else{
var no_kampus = document.querySelector("#qfront").value;
alert('Data Kost Sekitar Kampus ' + '"'+no_kampus+'"' + ' Belum Terdaftar!');
}
// Setup the different icons and shadows
var iconURLPrefix = 'http://maps.google.com/mapfiles/ms/icons/';
var icons = [
iconURLPrefix + 'red-dot.png',
iconURLPrefix + 'green-dot.png',
iconURLPrefix + 'blue-dot.png',
iconURLPrefix + 'orange-dot.png',
iconURLPrefix + 'purple-dot.png',
iconURLPrefix + 'pink-dot.png',
iconURLPrefix + 'yellow-dot.png'
]
var iconsLength = icons.length;
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(-37.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
streetViewControl: true,
panControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_BOTTOM
}
});
var infowindow = new google.maps.InfoWindow({
maxWidth: 160
});
var markers = new Array();
var iconCounter = 0;
// Add the markers and infowindows to the map
for (var i = 0; i < wwwsitus.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(wwwsitus[i][1], wwwsitus[i][2]),
map: map,
animation: google.maps.Animation.DROP,
icon: icons[iconCounter]
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(wwwsitus[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
iconCounter++;
// We only have a limited number of possible icon colors, so we may have to restart the counter
if(iconCounter >= iconsLength) {
iconCounter = 0;
}
}
function autoCenter() {
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
// Go through each...
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].position);
}
// Fit these bounds to the map
map.fitBounds(bounds);
}
autoCenter();
}
}
xmlhttp2.open("POST", "inc.php?q=" + str, true);
xmlhttp2.send(null);
}
}
xmlhttp.open("POST", "inc_num.php?q=" + str, true);
xmlhttp.send(null);
}
</script>
Input Field:
<input id="qfront" name="qfront" placeholder="Type your campus ..."
value="" type="text" onKeyPress="script_grabbed(this.value);" />
<input id="valdata" name="valdata" type="hidden" value=""/>
<input id="numvalue" name="numvalue" type="hidden" value=""/>
in num_inc.php:
$result = $uQuery->fetchColumn();
if($result> 0) {
echo $result;
}
in inc.php:
$googlemap=$result['googlemap'];
$map[] = $googlemap;
}
echo implode(', ' , $map);
NOTE: If you have another nice solution, please let me know. Of course, I like the better one than I attempt.
Complete Source: Github

The route is not being plotted when the waypoints exceeded a certain amount

I first read a sets of coordinates in my local drive, then put them in
the xcoord and y coord to be start,waypts,destination which will be plotted on Google Map.
But i discovered that, once the coodinates exceeding a certain number,the route is not plotted anymore,but a road map without and route. changing travelmode also changing the number of effective waypoints. What can be done when i have >100 coordinates to be plotted? Also, i would like to change all the marker into default one but not the green one with letters on it.(After 26 points the marker become normal again.) Thank you very much.
I was first using the example provided in a question about 8 waypoints, which is here:
Plotting more than 8 waypoints in Google Maps v3
My code are as follow:
xcoord = [];
ycoord = [];
stops = [] ;
document.getElementById('file').onchange = function(){
alert('4');
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
//alert(lines[line]);
var split = [];
split = lines[line].split(',');
window.xcoord.push(split[0]);
window.ycoord.push(split[1]);
}
alert('finish');
}
reader.readAsText(file);
};
jQuery(function() {
document.getElementById('button').onclick = function initMap(){
for(i = 0;i<xcoord.length;i++){
window.stops.push({"Geometry":{"Latitude":xcoord[i],"Longitude":ycoord[i]}});}
var map = new window.google.maps.Map(document.getElementById("map"));
// new up complex objects before passing them around
var directionsDisplay = new window.google.maps.DirectionsRenderer();
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map);
if (stops.length > 1)
window.tour.calcRoute(directionsService, directionsDisplay);}});
function Tour_startUp(stops) {
if (!window.tour) window.tour = {
updateStops: function (newStops) {
stops = newStops;
},
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, directionsDisplay) {
var myOptions = {
zoom: 13,
center: new window.google.maps.LatLng(22.2830, 114.200),
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
directionsDisplay.setMap(map);
},
fitBounds: function (map) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
jQuery.each(stops, function (key, val) {
var myLatlng = new window.google.maps.LatLng(val.Geometry.Latitude, val.Geometry.Longitude);
bounds.extend(myLatlng);
});
map.fitBounds(bounds);
},
calcRoute: function (directionsService, directionsDisplay) {
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops.length > 0;
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
for (var j = itemsCounter; j < stops.length; j++) {
subitemsCounter++;
subBatch.push({
location: new window.google.maps.LatLng(stops[j].Geometry.Latitude, stops[j].Geometry.Longitude),
stopover: true
});
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops.length;
// If it runs again there are still points. Minus 1 before continuing to
// start up with end of previous tour leg
itemsCounter--;
}
// now we should have a 2 dimensional array with a list of a list of waypoints
var combinedResults;
var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
var directionsResultsReturned = 0;
for (var k = 0; k < batches.length; k++) {
var lastIndex = batches[k].length - 1;
var start = batches[k][0].location;
var end = batches[k][lastIndex].location;
// trim first and last entry from array
var waypts = [];
waypts = batches[k];
waypts.splice(0, 1);
waypts.splice(waypts.length - 1, 1);
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: window.google.maps.TravelMode.WALKING
};
(function (kk) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
var unsortedResult = { order: kk, result: result };
unsortedResults.push(unsortedResult);
directionsResultsReturned++;
if (directionsResultsReturned == batches.length) // we've received all the results. put to map
{
// sort the returned values into their correct order
unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
var count = 0;
for (var key in unsortedResults) {
if (unsortedResults[key].result != null) {
if (unsortedResults.hasOwnProperty(key)) {
if (count == 0) // first results. new up the combinedResults object
combinedResults = unsortedResults[key].result;
else {
// only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
// directionResults object, but enough to draw a path on the map, which is all I need
combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
}
count++;
}
}
}
directionsDisplay.setDirections(combinedResults);
var legs = combinedResults.routes[0].legs;
// alert(legs.length);
for (var i=0; i < legs.length;i++){
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[i].start_location,"marker"+i,"some text for marker "+i+"<br>"+legs[i].start_address,markerletter);
}
var i=legs.length;
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[legs.length-1].end_location,"marker"+i,"some text for the "+i+"marker<br>"+legs[legs.length-1].end_address,markerletter);
}
}
});
})(k);
}
}
};
}
The Snap to road thing is done via loading coordinates using PHP and then
using the google api. the code is as follow(for less than 200 points):
<!DOCTYPE html>
<?php
$stringJoin = "";
$stringJoin2 = "";
$index = 0;
$handle = fopen($_GET['fileName'], "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$index++;
if ($index ==99 ){
$stringJoin2 .= trim($line)."|";
}
if ($index >= 100) {
$stringJoin2 .= trim($line)."|";
if($index == 200){
break;
}
continue;
}
$stringJoin .= trim($line)."|";
}
fclose($handle); }
echo $index;
echo "<br>";
$stringJoin = substr($stringJoin, 0, -1);
$stringJoin2 = substr($stringJoin2, 0, -1);
echo $stringJoin;
echo "<br>";
echo $stringJoin2; ?>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Roads API Demo</title>
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#bar {
width: 240px;
background-color: rgba(255, 255, 255, 0.75);
margin: 8px;
padding: 4px;
border-radius: 4px;
}
#autoc {
width: 100%;
box-sizing: border-box;
}
</style>
</head>
<body>
<input type="button" name="button" id="button">
<input type="file" name="file" id="file">
<div id="map"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places"></script>
<script>
var apiKey = 'AIzaSyCk5PjtR_spPKrVowRS3A7I3IE4gX6Ctec';
var map;
var drawingManager;
var placeIdArray = [];
var placeIdArray2 = [];
var polylines = [];
var polylines2 = [];
var snappedCoordinates = [];
var snappedCoordinates2 = [];
document.getElementById('button').onclick = function initialize() {
alert("Start");
var mapOptions = {
zoom: 13,
center: {lat: 22.3030, lng: 114.200} };
map = new google.maps.Map(document.getElementById('map'), mapOptions);
runSnapToRoad();
runSnapToRoad2();}
// Snap a user-created polyline to roads and draw the snapped path
function runSnapToRoad() {
$.get('https://roads.googleapis.com/v1/snapToRoads', {
interpolate: true,
key: apiKey,
path: <?php echo '"'.$stringJoin.'"';?>}, function(data) {
processSnapToRoadResponse(data);
drawSnappedPolyline();
//getAndDrawSpeedLimits(); });}
// Store snapped polyline returned by the snap-to-road method.
function processSnapToRoadResponse(data) {
snappedCoordinates = [];
placeIdArray = [];
for (var i = 0; i < data.snappedPoints.length; i++) {
var latlng = new google.maps.LatLng(
data.snappedPoints[i].location.latitude,
data.snappedPoints[i].location.longitude);
snappedCoordinates.push(latlng);
placeIdArray.push(data.snappedPoints[i].placeId); }}
// Draws the snapped polyline (after processing snap-to-road response).
function drawSnappedPolyline() {
var snappedPolyline = new google.maps.Polyline({
path: snappedCoordinates,
strokeColor: 'black',
strokeWeight: 3 });
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);}
</script>
<div id="bar">
<p class="auto"><input type="text" id="autoc"/></p>
<p><a id="clear" href="#">Click here</a> to clear map.</p>
</div>

Google Map Condition on Town

I want a condition on my code where user input start point and end point, I want to make a check on start point to check that it is located in London or not so I find this code which work well in function but I want its variable town make function outside of this function so I create the checkpoint.
var input = document.getElementById('start');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
// when user has clicked on an autocomplete suggestion
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
// get town of selected place
function getTown(address_components) {
var geocoder = new google.maps.Geocoder(); result = address_components;
var info = [];
for (var i = 0; i < result.length; ++i) {
if (result[i].types[0] == "locality") {
return result[i].long_name;
}
}
};
var town = getTown(place.address_components);
// if place is in London, move marker to the place
if (town == 'London') {
alert('in London');
} else {
// if not, do nothing and alert user
alert('you must click on a place in London');
}
});
How can I access var town outside of this function on whole page so I make condition on base of it?
You can make a variable outside of the scope of the callback to set the result to.
var input = document.getElementById('start');
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 12,
center: {lat: 51.507351, lng: -0.127758}
});
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var town;
// when user has clicked on an autocomplete suggestion
google.maps.event.addListener(autocomplete, 'place_changed', function() {
function getTown(address_components) {
result = address_components;
var info = [];
for (var i = 0; i < result.length; ++i) {
if (result[i].types[0] == "locality") {
return result[i].long_name;
}
}
};
document.getElementById('place').innerHTML = '';
document.getElementById('town').innerHTML = '';
town = getTown(autocomplete.getPlace().address_components);
});
function inLondonCheck(placeName) {
document.getElementById('place').innerHTML = placeName + " in London? " + (town === 'London');
document.getElementById('town').innerHTML = town || '';
}
setInterval(function() {
if (town) inLondonCheck(autocomplete.getPlace().name);
}, 500);
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<input id="start">
<div>Place<pre id="place"></pre></div>
<div>Town<pre id="town"></pre></div>
<div id="map-canvas"></div>

IE throws errors parsing data for GoogleMap

I have added map displaying some elements with specific geo position using Google.API. In modern browsers everything works fine, but IE7/8 as always has some problems. When trying to center map using lat/long parameters of each element I'm getting error stating , that 'lat' is "empty or not an object" in line var pos_lat = parseFloat(data_map[i]['lat']);. Still marker is added in the proper place using the same data. Anyone had this kind of problem ?
<script type='text/javascript'>
var map;
var mapStart = function(){
if(GBrowserIsCompatible()){
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(51.961869,19.134521),6);
map.addControl(new GLargeMapControl());
var icon1 = new GIcon();
icon1.image = "/static/images/map_icon_1.png";
icon1.iconSize = new GSize(36, 30);
icon1.infoWindowAnchor = new GPoint(16,16);
icon1.iconAnchor = new GPoint(16,16);
var data_map = [{'url': '/bo/properties/property/7/', 'lat': '52.1898985', 'long': '20.8461914', 'name': 'asdfgh'},]
mapa.enableDoubleClickZoom();
mapa.enableContinuousZoom();
var bounds = new GLatLngBounds();
var maxlng =0;
var maxlat=0;
var minlng=0;
var minlat=0;
var positions=0;
var zoom = 0;
for (var i=0; i < data_map.length; i++){
var pos_lat = parseFloat(data_map[i]['lat']);
var pos_lon = parseFloat(data_map[i]['long']);
if(!isNaN(pos_lat) && !isNaN(pos_lon)){
positions = 1;
zoom++;
addMarker(pos_lat, pos_lon,{icon:icon1});
if (pos_lat < minlat || minlat==0){ minlat = pos_lat}
if (pos_lat > maxlat || maxlat==0){ maxlat = pos_lat}
if (pos_lon < minlng || minlng==0){minlng = pos_lon}
if (pos_lon > maxlng || maxlng==0){maxlng = pos_lon}
lat = minlat + (( maxlat - minlat)/2);
lng = minlng + (( maxlng - minlng)/2);
var allpoints = new GLatLng(lat,lng);
bounds.extend(allpoints);
}
}
if(positions){
if(zoom > 2){
mapa.setZoom(map.getBoundsZoomLevel(bounds)-2);
}
else{
map.setZoom(10);
}
map.setCenter(bounds.getCenter());
}
}
}
var addMarker = function(lat, lon, options){
point = new GLatLng(lat,lon);
var marker = new GMarker(point, options);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(info_box_html);
});
map.addOverlay(marker);
}
$(document).ready(function(){
mapStart();
});
window.onunload = function (){ GUnload()};
</script>
var data_map = [{'url': '/bo/properties/property/7/', 'lat': '52.1898985', 'long': '20.8461914', 'name': 'asdfgh'},]
There is an extra comma at the end of array.
Also try to use data_map[i].lat instead of data_map[i]['lat']

Categories

Resources