Google Maps and Yelp API mash-up doesn't work with some searchterms - api

I am currently working on a webapplication mashing up the Yelp and Google Maps API's. I finished the code and it seemed to be working until I found out that google maps won't show up with certain searchterms. For example when I search for Pizza in Denver my app works perfectly, but when i search for Sushi in New York, Google Maps just doesn't load. I checked my source code after doing the search and the results are all there. I can't seem to figure out what's the problem. The app is online .
The Google Maps code snippet:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
//Er word een kaart neergezet
function initialize(lat,lon,label) {
var lancenter =
"<?
echo $latitude_center
?>";
var loncenter =
"<?
echo $longitude_center
?>";
var map;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(lancenter, loncenter),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var companyLogo = new google.maps.MarkerImage('image.png',
new google.maps.Size(35,60),
new google.maps.Point(0,0),
new google.maps.Point(18,60)
);
var companyShadow = new google.maps.MarkerImage('shadow.png',
new google.maps.Size(69,60),
new google.maps.Point(0,0),
new google.maps.Point(18,60)
);
<?
//Er word een loop gemaakt die de array met resultaten doorloopt en vervolgens markers, infowindows en beschrijving op de kaart plaatst voor alle resultaten.
while($i<sizeof($response["businesses"])) {
$latitude_result = $response["businesses"][$i]["location"]["coordinate"]["latitude"];
$longitude_result = $response["businesses"][$i]["location"]["coordinate"]["longitude"];
$result_description = $response["businesses"][$i]["name"];
$result_rating = $response["businesses"][$i]["rating_img_url_small"];
$result_ratingnr = $response["businesses"][$i]["review_count"];
$result_beschrijving = $response["businesses"][$i]["snippet_text"];
$result_beschrijving=str_replace("\n"," ",$result_beschrijving);
$result_beschrijving=str_replace("\r"," ",$result_beschrijving);
$result_adres0 = $response["businesses"][$i]["location"]["display_address"][$i];
$result_adres1 = $response["businesses"][$i]["location"]["display_address"]["1"];
$result_adres2 = $response["businesses"][$i]["location"]["display_address"]["2"];
$result_adres3 = $response["businesses"][$i]["location"]["display_address"]["3"];
$result_image = $response["businesses"][$i]["image_url"];
$result_url = $response["businesses"][$i]["url"];
$result_image = $result_image ? $result_image : 'noimg.gif';
$result_beschrijving = $result_beschrijving ? $result_beschrijving : 'Er is helaas geen beschrijving beschikbaar voor deze locatie.';
?>
var lanresult =
"<?
echo $latitude_result
?>";
var lonresult =
"<?
echo $longitude_result
?>";
var resultloc = new google.maps.LatLng(lanresult, lonresult);
var beschrijving =
'<h3>'+"<?
echo "<div id='container'>",Naam,":"," ","<h2>", $result_description,"</h2>","</br>",Beschrijving,":"," ","<h2>", $result_beschrijving,"<a href='", $result_url,"' target='_new'>","Lees verder","</a>","</h2>","</br>", Adres,":"," ","<h2>", $result_adres0,"</br>", $result_adres1,"</h2>","</br>", Waardering,":"," ","<img src='", $result_rating,"'/>","<h2>",$result_ratingnr," ",recensies,"</h2>","</br>","<img src='", $result_image,"'/>","</br>","</br>","<h2>","<a href='", $result_url,"' target='_new'>","Lees meer informatie via YELP","</a>","</h2>","</div>"
?>";'</h3>'
var marker<? echo $i; ?> = new google.maps.Marker({
map: map,
icon: companyLogo,
shadow: companyShadow,
position: resultloc,
});
var infowindow<? echo $i; ?>= new google.maps.InfoWindow({
content: beschrijving,
maxWidth: 260
});
google.maps.event.addListener(marker<? echo $i; ?>, 'click', function() {
infowindow<? echo $i; ?>.open(map,marker<? echo $i; ?>);
});
<?
$i++;
} // einde while php
?>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I really hope someone can help me.
Kind Regards

Related

Google map API isn't working

<!DOCTYPE html>
<?php
/* lat/lng data will be added to this array */
try{$work=$_GET["service"];}catch(Exception $e){echo 'Authorization Failed.Map may Misbehave or Buggy.Click here to report this';}
$locations=array();
$uname="root";
$pass="";
$servername="localhost";
$dbname="bcremote";
$db=new mysqli($servername,$uname,$pass,$dbname);
$query = $db->query('SELECT * FROM location');
while( $row = $query->fetch_assoc() ){
$name = $row['uname'];
$longitude = $row['longitude'];
$latitude = $row['latitude'];
$link=$row['link'];
/* Each row is added as a new array */
$locations[]=array( 'name'=>$name, 'lat'=>$latitude, 'lng'=>$longitude, 'lnk'=>$link );
}
//echo $locations[0]['name'].": In stock: ".$locations[0]['lat'].", sold: ".$locations[0]['lng'].".<br>";
//echo $locations[1]['name'].": In stock: ".$locations[1]['lat'].", sold: ".$locations[1]['lng'].".<br>";
?>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAfFN8NuvYyNkewBVMsk9ZNIcUWDEqHg2U&callback=initMap()"
async defer></script>
<script>
//var myLatLng = {lat: -25.363, lng: 131.044};
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
scrollwheel: false,
zoom: 10
});
<?php for($i=0;$i<sizeof($locations);$i++)
{ ?>
var marker = new google.maps.Marker({
map: map,
position: {lat: <?php echo $locations[$i]['lat']?>,lng: <?php echo $locations[$i]['lng']?>},
title: 'Service',
url: 'https://<?php echo $locations[$i]['lnk']?>'
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = marker.url;
});
<?php } ?>
}
</script>
<body>
<div id="map"></div>
</body>
I have a Code like this. I think don't have any Errors in code side may be in Logic Side. Please help me to over come this. I need to submit this Project within next 2 Days.May I know how to fix this Issue?
With Advanced Thanks,
Kavin
It seems that the Problem was with Google Map Key and the way that I handled it. Now it works perfectly. Once I have updated it, It started Working. The Code is also changed with a Help of GitHub Repository.
<?php
$locations=array();
$work=$_GET["service"];
$uname="root";
$pass="";
$servername="localhost";
$dbname="bcremote";
$db=new mysqli($servername,$uname,$pass,$dbname);
$query = $db->query("SELECT * FROM location where work='$work'");
//$number_of_rows = mysql_num_rows($db);
//echo $number_of_rows;
while( $row = $query->fetch_assoc() ){
$name = $row['uname'];
$longitude = $row['longitude'];
$latitude = $row['latitude'];
$link=$row['link'];
/* Each row is added as a new array */
$locations[]=array( 'name'=>$name, 'lat'=>$latitude, 'lng'=>$longitude, 'lnk'=>$link );
}
//echo $locations[0]['name'].": In stock: ".$locations[0]['lat'].", sold: ".$locations[0]['lng'].".<br>";
//echo $locations[1]['name'].": In stock: ".$locations[1]['lat'].", sold: ".$locations[1]['lng'].".<br>";
?>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAfFN8NuvYyNkewBVMsk9ZNIcUWDEqHg2U"></script>
<script type="text/javascript">
var map;
var Markers = {};
var infowindow;
var locations = [
<?php for($i=0;$i<sizeof($locations);$i++){ $j=$i+1;?>
[
'AMC Service',
'<p>Book this Person Now</p>',
<?php echo $locations[$i]['lat'];?>,
<?php echo $locations[$i]['lng'];?>,
0
]<?php if($j!=sizeof($locations))echo ","; }?>
];
var origin = new google.maps.LatLng(locations[0][2], locations[0][3]);
function initialize() {
var mapOptions = {
zoom: 9,
center: origin
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
infowindow = new google.maps.InfoWindow();
for(i=0; i<locations.length; i++) {
var position = new google.maps.LatLng(locations[i][2], locations[i][3]);
var marker = new google.maps.Marker({
position: position,
map: map,
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][1]);
infowindow.setOptions({maxWidth: 200});
infowindow.open(map, marker);
}
}) (marker, i));
Markers[locations[i][4]] = marker;
}
locate(0);
}
function locate(marker_id) {
var myMarker = Markers[marker_id];
var markerPosition = myMarker.getPosition();
map.setCenter(markerPosition);
google.maps.event.trigger(myMarker, 'click');
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body id="map-canvas">

Google Maps Api With Asp.net MVC 4 PartialView Ajax Request

I have a partial view. This partial view returns by Ajax.actionlink request. Partial View contain a google map . But map not rendering couse scripts must run when document is ready.
How to show google map in a partial view result ?
Partial View scripts :
var markers = [];
markercount = 0;
var zoom = 7;
var G = google.maps;
var map;
function initializeMap() {
var centerPoint = new G.LatLng(45.5, -100.5);
var myOptions = {
center: centerPoint,
zoom: zoom,
mapTypeId: G.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
myOptions);
addPolygon(map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
var input = (
document.getElementById('autocomplate'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(map, 'click', addMarker);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setIcon(({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initializeMap);
I solved with this.
#Ajax.ActionLink(" ", "EditRestaurant", "Admin", New With {.RestID = Model(i).RestaurantID}, New AjaxOptions With {.HttpMethod = "POST",
.InsertionMode=InsertionMode.Replace,
.UpdateTargetId="edit",
.OnSuccess="map"}, New With {.Class = "glyphicon glyphicon-zoom-out"})
script
function map()
{
initializeMap();
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, 'load', initializeMap);
}

marker clusterer doesn't cluster when zoom

i'm trying to learn google api and i want to use marker clusterer. i create a database
from here and do whatever google said. my code is
`
<script src="markerclusterer.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'images/pin1.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'images/pin2.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function initialize() {
var markers = null;
var mcmarkers = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 12,
mapTypeId: 'satellite'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"))
var point = new google.maps.LatLng(lat, lng);
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
mcmarkers.push(marker);
var mc = new MarkerClusterer(map, mcmarkers);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('POST', url, true);
request.send(null);
}
function doNothing() {}
//]]>
google.maps.event.addDomListener(window, 'load', initialize);
`
it works well when i open for the first time but when i zoom in or out there was no clusters except max zoom out. i couldn't figure it out. thanks for your help...
var mc = new MarkerClusterer(map, mcmarkers);
This line cannot be placed inside the for loop. but outside after it. I did exactly the same mistake:).

Multiple Bing Map Pushpins from SQL not showing in Firefox & Chrome but do in IE

I'm displaying a Bing Map (v7) in my Webmatrix2 website with a series of pushpins & infoboxes drawn from a SQL Express database using a JSON enquiry.
While the maps appears in all 3 browsers I'm testing (IE, FF & Chrome) the pushpins are sometimes not showing in FF & Chrome, particularly if I refresh with Cntrl+F5
This is my first JSON and Bing Maps app so expect there's a few mistakes.
Any suggestions on how to improve the code and get display consistency?
#{
Layout = "~/_MapLayout.cshtml";
}
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<link rel="StyleSheet" href="infoboxStyles.css" type="text/css">
<script type="text/javascript">
var map = null;
var pinLayer, pinInfobox;
var mouseover;
var pushpinFrameHTML = '<div class="infobox"><a class="infobox_close" href="javascript:closeInfobox()"><img src="/Images/close2.jpg" /></a><div class="infobox_content">{content}</div></div><div class="infobox_pointer"><img src="images/pointer_shadow.png"></div>';
var pinLayer = new Microsoft.Maps.EntityCollection();
var infoboxLayer = new Microsoft.Maps.EntityCollection();
function getMap() {
map = new Microsoft.Maps.Map(document.getElementById('map'), {
credentials: "my-key",
zoom: 4,
center: new Microsoft.Maps.Location(-25, 135),
mapTypeId: Microsoft.Maps.MapTypeId.road
});
pinInfobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(0, 0), { visible: false });
AddData();
}
$(function AddData() {
$.getJSON('/ListSchools', function (data) {
var schools = data;
$.each(schools, function (index, school) {
for (var i = 0; i < schools.length; i++) {
var pinLocation = new Microsoft.Maps.Location(school.SchoolLat, school.SchoolLon);
var NewPin = new Microsoft.Maps.Pushpin(pinLocation);
NewPin.title = school.SchoolName;
NewPin.description = "-- Learn More --";
pinLayer.push(NewPin); //add pushpin to pinLayer
Microsoft.Maps.Events.addHandler(NewPin, 'mouseover', displayInfobox);
}
});
infoboxLayer.push(pinInfobox);
map.entities.push(pinLayer);
map.entities.push(infoboxLayer);
});
})
function displayInfobox(e) {
if (e.targetType == "pushpin") {
var pin = e.target;
var html = "<span class='infobox_title'>" + pin.title + "</span><br/>" + pin.description;
pinInfobox.setOptions({
visible: true,
offset: new Microsoft.Maps.Point(-33, 20),
htmlContent: pushpinFrameHTML.replace('{content}', html)
});
//set location of infobox
pinInfobox.setLocation(pin.getLocation());
}
}
function closeInfobox() {
pinInfobox.setOptions({ visible: false });
}
function getCurrentLocation() {
var geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);
geoLocationProvider.getCurrentPosition();
}
</script>
<body onload="getMap();">
<div id="map" style="position:relative; width:800px; height:600px;"></div>
<div>
<input type="button" value="Find Nearest Schools" onclick="getCurrentLocation();" />
</div>
</body>
The JSON file is simply
#{
var db = Database.Open("StarterSite");
var sql = #"SELECT * FROM Schools WHERE SchoolLon != ' ' AND SchoolLon != 'null' ";
var data = db.Query(sql);
Json.Write(data, Response.Output);
}
Add your pinLayer, infobox, and infoboxLayer before calling the AddData function and see if that makes a difference. Also verify that school.SchoolLat and school.SchoolLon are numbers and not a string version of a number. If they are a string, then use parseFloat to turn them into a number. Other than that everything looks fine.

Google maps infowindow doesnt show up anymore

Good morning,
A former colleague of mine had created an application where you could search by zipcode and then placed markers on the map (google maps) in a radius of 5-40 km.
The locations are stores in a radius of 40 km from the zip code where you are looking for.
The function itself is still working only the info window with the information does not work anymore.
I have several websites running with this application but for all sites the infowindow is not working anymore. Could it be that Google itself has made ​​adjustments in the api and I also need to adjust something somewhere?
This is the code that my colleague has put together and there is nothing changed but it does not work anymore ... Is there someone here know anything about the problem because I can not figure out myself..
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: <?php
if(is_array($postcodevelden) && count($postcodevelden) > 0 && !empty($_POST['address']))
{
switch($radius)
{
case "5":
echo "12";
break;
case "10":
echo "11";
break;
case "15":
case "20":
echo "10";
break;
case "30":
case "40":
echo "9";
break;
}
}
else
{
echo "7";
}
?>,
center: new google.maps.LatLng(<?php if(is_array($postcodevelden) && count($postcodevelden) > 0) { echo $lat.", ".$lon; } else { echo "52.2008737173322, 5.25146484375"; } ?>),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
if(is_array($adressen) AND count($adressen) > 0)
{
foreach($adressen as $adres)
{
$afstand = round((6371 * acos(sin(deg2rad($lat)) * sin(deg2rad($adres->locatie_lat)) + cos(deg2rad($lat)) * cos(deg2rad($adres->locatie_lat)) * cos(deg2rad($adres->locatie_lon) - (deg2rad($lon))))), 2);
?>
addMarker(<?php echo $adres->locatie_lat.", ".$adres->locatie_lon.", '".$adres->locatie_naam."', '".$adres->locatie_straat."', '".$adres->locatie_postcode."', '".$adres->locatie_plaats."', '".$adres->locatie_telefoon."', '".$afstand."'"; ?>);
<?php
}
}
?>
}
var infowindow = new google.maps.InfoWindow();
function addMarker(lat, lon, naam, straat, postcode, plaats, telefoon, afstand)
{
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
icon: "images/pincard/wheel-icon.png",
title: naam
});
google.maps.event.addListener(marker, 'mouseover', function() {
var contentString = '<div>'+
'<b style="border-bottom: 1px solid #000000;">' + naam + '</b><br/>'+
'Afstand (hemelsbreed): ' + afstand + ' km<br/>' +
straat + '<br/>' +
postcode + ' ' + plaats + '<br/>';
if(telefoon != "")
{
contentString = contentString + 'Telefoonnr: ' + telefoon;
}
contentString = contentString + '</div>';
infowindow.content = contentString;
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function(){
infowindow.close(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I call the api like this:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
If anyone has any idea why the info window to all websites stops working then I would love to hear that because I do not understand why it no longer works.
Thanks in advance for any effort
Kind regards,
Joep
PS: this is a website for example:
intertyre...php?lang=nl&p=4
I was bitten by the same problem and went Googling for an answer.
Found the answer to my problem -- it looks like Google may have tightened up its infoWindow API a bit forcing you to set
the .content member via a proper Set() function.
Try replacing the line
infowindow.content = contentString;
with
infowindow.setContent(contentString);
and see if that helps. I did that with my code and that fixed the breakage.