Google map API isn't working - api

<!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">

Related

How do I Set Up Clustering on Google Maps Web API

I'm trying to add clustering to Google Maps web project, but so far no luck. Here is what is working:
Added a few markers
Requested user location (code removed).
markercluster.js is the library file downloaded from the GitHub project and saved in the public.html file.
I have removed the API key for security.
JavaScript Code in HTML Body
var userPosition;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
//center: {lat: -34.928499, lng: 138.600746},
center: {lat: -33.86882, lng: 151.209296},
zoom: 13
});
var markers = [
{coords:{lat:-34.923885, lng:138.562042}, content:'<p><strong>British Raj</strong></p>'},
{coords:{lat:-34.924476, lng:138.561141}, content:'<p><strong>Subway (Torrensville)</strong></p>'},
{coords:{lat:-34.843645, lng:138.507653}, content:'<p>Banyan Hotel Port Adelaide</p>'},
{coords:{lat:-34.92366, lng:138.567063}, content:'<p>Abyssinian Restaurant</p>'},
{coords:{lat:-34.923927, lng:138.561959}, content:'<p>Burger Foundry (Torrensville)</p>'}
];
var gmarkers = [];
for(var i = 0; i < markers.length; i++){
//addMarker(markers[i]);
gmarkers.push(addMarker(markers[i]));
}
function addMarker(props){
var marker = new google.maps.Marker({
position:props.coords,
map:map,
icon:'Layer 1.png'
});
if (props.content){
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('click', function(){
infoWindow.open(map, marker);
});
}
}
}
var markerCluster = new MarkerClusterer(map, gmarkers,{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY_REMOVED&callback=initMap"
async defer></script>
<script src="markercluster.js"></stript>
CSS
html, body{
height: 100%;
padding: 0;
margin: 0;
}
#map {
height: 80%;
weidth: 80%;
}
There are several issues with your code:
The creation of the MarkerClusterer is outside of the initMap function, so it runs before the API is loaded. Move that inside the initMap function.
The addMarker function doesn't return anything, so everytime you create a marker you add "undefined" to the gmarkers array (add: return marker; to the end of the function).
Based on the example in the documentation, you need to load markerclusterer.js before the Google Maps JavaScript API v3.
proof of concept fiddle
code snippet:
var userPosition;
var gmarkers = [];
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
//center: {lat: -34.928499, lng: 138.600746},
center: {
lat: -33.86882,
lng: 151.209296
},
zoom: 13
});
var markers = [
{coords:{lat:-34.923885, lng:138.562042}, content:'<p><strong>British Raj</strong></p>'},
{coords:{lat:-34.924476, lng:138.561141}, content:'<p><strong>Subway (Torrensville)</strong></p>'},
{coords:{lat:-34.843645, lng:138.507653}, content:'<p>Banyan Hotel Port Adelaide</p>'},
{coords:{lat:-34.92366, lng:138.567063}, content:'<p>Abyssinian Restaurant</p>'},
{coords:{lat:-34.923927, lng:138.561959}, content:'<p>Burger Foundry (Torrensville)</p>'}
];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
//addMarker(markers[i]);
gmarkers.push(addMarker(markers[i]));
bounds.extend(markers[i].coords);
}
map.fitBounds(bounds);
function addMarker(props) {
var marker = new google.maps.Marker({
position: props.coords,
map: map,
});
if (props.content) {
var infoWindow = new google.maps.InfoWindow({
content: props.content
});
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
return marker;
}
var markerCluster = new MarkerClusterer(map, gmarkers, {
imagePath: 'https://unpkg.com/#google/markerclustererplus#4.0.1/images/m'
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://unpkg.com/#googlemaps/markerclustererplus/dist/index.min.js"></script>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Return data using a marker in Google Maps v3

Is it possible return the street addres, province, zip code (postal code), city and country using a marker in Google Maps v3?
Sometimes not return all data using formatted_address.
Is there a way that I can return something especific? E.g. return[1].city, return[1].country, return[1].Address...
Yes.
I wrote a function that reads components from the geocoder results.
Here is a full example
<!doctype html>
<html>
<head>
<style>
#map-canvas {
width: 500px;
height: 400px;
}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
function init() {
var center = new google.maps.LatLng(50.845464, 4.3571121); // Brussels
var geocoder;
geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(
document.getElementById('map-canvas'), {
center: center,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
draggable: true,
title: "Drag me to see the address components",
map: map,
position: center
});
google.maps.event.addListener(marker, 'dragend', function(e) {
document.getElementById('display').innerHTML = '';
var pos = marker.getPosition();
// get geoposition
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
// get postal code
var postal_code = addresComponent('postal_code', responses[0])
if (postal_code) {
document.getElementById('display').innerHTML += '<div>Postal code: ' + postal_code + '</div>';
}
// get street
var street = addresComponent('route', responses[0])
if (street) {
document.getElementById('display').innerHTML += '<div>Street: ' + street + '</div>';
}
// street number (number of the house in the street)
var street_number = addresComponent('street_number', responses[0])
if (street_number) {
document.getElementById('display').innerHTML += '<div>Street number: ' + street_number + '</div>';
}
}
});
});
}
/**
* geocodeResponse is an object full of address data.
* This function will "fish" for the right value
*
* example: type = 'postal_code' =>
* geocodeResponse.address_components[5].types[1] = 'postal_code'
* geocodeResponse.address_components[5].long_name = '1000'
*
* type = 'route' =>
* geocodeResponse.address_components[1].types[1] = 'route'
* geocodeResponse.address_components[1].long_name = 'Wetstraat'
*/
function addresComponent(type, geocodeResponse) {
for(var i=0; i < geocodeResponse.address_components.length; i++) {
for (var j=0; j < geocodeResponse.address_components[i].types.length; j++) {
if (geocodeResponse.address_components[i].types[j] == type) {
return geocodeResponse.address_components[i].long_name;
}
}
}
return '';
}
</script>
</head>
<body onload="init()">
<div id="map-canvas"></div>
<div id="display"></div>
<h3>drag the marker - see some address components</h3>
</body>
</html>

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:).

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.