Google Maps API requires refresh to work correctly - javascript

I have problem coding the google maps API for my personal website. The google maps doesn't work until I refresh the browsers. Below are the scripts for google maps.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&v3"></script>
<script type="text/javascript" src="<?php echo get_bloginfo('template_url'); ?>/js/mk.js"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new MarkerWithLabel({
position: results[0].geometry.location,
map: map,
labelContent: address,
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 1.0}
});
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
initialize();
codeAddress("<?php
global $post;
$pid = $post->ID;
$terms = wp_get_post_terms($pid,'ad_location');
foreach($terms as $term)
{
echo $term->name." ";
}
$location = get_post_meta($pid, "Location", true);
echo $location;
?>");
</script>
Did I missed anything for the scripts? I didn't add API on it, but the console said "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

You need to make sure the map variable is initialized before you pass it to markerOptions.
A bit of overzealous debugging showed me that on the times that the page fails, the map is still undefined.
The $(document).ready() will usually occur before body.onload, so either put a call to initialize() at the very top of your $(document).ready(function() { ... }); or put the code for initialize in there.
Also, though not strictly necessary, you should consider encapsulating your map variable instead of using a global.

Related

(Google Map API) Geocode was not successful for the following reason: REQUEST_DENIED

I am new to this place and I desperately need help from experts here! D=
I tried to make a page that can generate dynamic numbers of google map. The webpage, however, keep showing Geocode was not successful for the following reason: REQUEST_DENIED.
I double checked my google API console and confirmed that the geocoding API and Javascript API are enabled. (I literally enabled all Google map API in the list...)
My Google Map API List
Can someone please take a look and tell me why? T_T
//------------------------------------------------\\
Below is my javascript and html button:
Javascript:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=APIkey&callback=initMap"
type="text/javascript"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=mapAddress"
type="text/javascript"></script>
<!-- &callback=mapAddress -->
<script>
function mapAddress(mapElement, address) {
var geocoder = new google.maps.Geocoder();
// alert(mapElement);
// alert(address);
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = {
zoom: 17,
center: results[0].geometry.location,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
HTML(Supposed to be php variable):
<button type="button" class="button_mapAPI" id="address_<?php echo $case["id"]; ?>" value="<?= $case['location_detail'] ?>" onclick="mapAddress('map1', 'Hong Kong')"/>Map Refresh</button>
Did you enable the Billing for API Key? Google Maps is no longer free. You have to associate a credit card so that you can get billed if your site has requests that exceed the $200 credit they give you monthly for free.
First of all, the problem was loading the scripts as async, remove it..
try that jsfiddle with your API KEY
(function(){
let mapElement = 'map';
let address = 'SPAIN';
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = {
zoom: 17,
center: results[0].geometry.location,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
})();
#map {
width: 100%;
height: 350px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY" type="text/javascript"></script>
<div id="map"></div>
Nead to enable geocoding api that convert address to coordinates and it is a bit pricier, use coordinates instead of address and no need for Geocoding API

How to specify location in google map?

I want to specify location in google map, I have javascript codes work fine but I do know how I can specify location from php variable
Below are sample codes.
<html>
<head>
<title></title>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCqgya6hvq6zu3Z2xeT5xEGPPi5pY2ize4&callback=initMap"></script>
</head>
<body>
<?php
//I want to search this location in google map
$location="Kigali Rwanda";
?>
<script>
var myMap;
var myLatlng = new google.maps.LatLng(52.518903284520796,-1.450427753967233);
function initialize() {
var mapOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP ,
scrollwheel: false
}
myMap = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: myMap,
title: 'Name Of Business',
icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map" style="width:500px; height: 500px;">
</div>
</body>
</html>
Please anyone can help me
You can use Geocoding service in this case
function initMap() {
//var address = '<?php echo $location ?>';
var address = 'Kigali Rwanda';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
});
}
#map {
height: 400px;
width: 100%;
}
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
you have to use lat, lng to specifiy location. In case of country or state name you should get lat, lng of the location and define it in the code. insert the value of php variable in hidden input field. On running script get the value and process it.

Google map v2 to v3 code

I am working on a migration project from google maps V2 to V3 and wrote the bellow code but
getting error and unable to solve the problem.
Am i using wrong method of google maps?
What is wrong in this code?
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key='. $mapKey .'&sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( $_ADDRESS );
// initialize map
function initialize()
{
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.getPosition( address, function(point)
{
if (!point)
{
alert(address + " not found");
}
else
{
map.setCenter(point, 13);
var marker = new google.maps.Marker(point);
map.addOverlay(marker);
//marker.openInfoWindowHtml(address);
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Any idesa?
Thanks
I have split these answers as the first deals with the fundamentals of the javascript, this then deals with using the Google Maps API.
As I've never used the maps API, I can't comment on V2, but looking at how you do things in V3, I think this does what you're looking for...
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( "$_ADDRESS" );
// initialize map
function initialize( address )
{
map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.geocode( { "address": address }, function( results, status )
{
if ( status == google.maps.GeocoderStatus.OK )
{
position = results[0].geometry.location;
map.setCenter(position, 13);
var marker = new google.maps.Marker({ map: map, position: position });
}
else
{
alert(address + " not found");
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Having said that, I'd question the str_replace straight into the javascript - can you trust the source of that data? If not, then you should look up how to sanitise that string before you put it into your javascript or you may allow people to inject code into your site.
Looking at the fundamental javascript issues you have...
Try adding quotes around the string that you're replacing into the javascript
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
Becomes:
echo $map = str_replace('$_ADDRESS', "'MYADDRESS'", $map );
That way the string that contains the address in javascript is properly quoted.
Also, ensure that you can receive the address in your initialize function:
function initialize()
Becomes:
function initialize( address )
Finally, do not redeclare "map" when you assign it a value in "initialize", otherwise you are referencing a different variable that only exists in that function:
var map = new google.maps.Map(document.getElementById("map_canvas"), {
Becomes:
map = new google.maps.Map(document.getElementById("map_canvas"), {

Google Maps with Geocode returning null

I'm using Google Maps to place markers from an array of zip codes but it only places about 10% of them. The rest return null results. I can't find the problem. Here is my code.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
var latlng = new google.maps.LatLng(37.09024, -95.712891);
var map = new google.maps.Map(document.getElementById('pledge-map'), {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var geocoder = new google.maps.Geocoder();
var locations = <?php echo(json_encode($zips)); ?>
for (var i = 0; i < locations.length; i++) {
geocoder.geocode( { 'address': locations[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
}
});
}
</script>
locations is an array of zip code:
locations =["20190","22192","20148","06078","95136","84120","53066","53404","48323","52404","72762","89701","39667","78073","78016","76013","15613","84010","77662","77407","30127","94566","14625","45629","27406","27289","02339","01864","39116","77079","10954","37683","72801","19341","14580","64133","29579","08527","32258","33433","60093","76691","78261","77095","19426","10469","92038","85208","67220","61031","85706","72223","21222","66224","34242","30224","56232","32746","08558","72712","14209","43015","52722","32779","33518","33578","60565","11239","17007","60623","77469","20165","20002","36116","20769","20815","34209","02301","60025","48158","38804","30736","01803","45040","48069","07463","53018","73008","80951","70785","72065","91510","91506","67209","22408","36849"]
The geocoder is subject to a quota and rate limits. you are not checking for the error case (there is no code if the status returned is not OK).
Either:
look for the quota exceeded error code and handle it intelligently (add a delay and retry, only add the marker if it succeeds)
geocode the zipcodes offline and store the coordinates, use those to display your markers.

Get or set google geocode maps in iframe src via javascript

I need to use Google maps v3 "GeoCode" dynamically.
i.e. I need to call / use a JS function from my php code (which generates storeDetail in a foreach loop ex dbase), from the src= attribute of an IFrame.
what I have done is not working....appreciate help with this.
I have: (in my db for each loop, with some other tr td stuff)
<tr><td rowspan='10' width='100' valign='top' height="150">
<iframe src="="<script>document.write(codeAddress(<?=$row->BrAddress;?>));</script>">"
name="<?=$row->BrAddress;?>" id="<?=$row->BrAddress;?>" scrolling="no" bgcolor="#fffff"> </iframe></td></tr>
and my Js is
var geocoder;
var map;
function codeAddress(address)
var myOptions = {zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP};
//each IFrame has the name ex db BrAdress field, "<?=$row->BrAddress;?>"
map = new google.maps.Map(document.getElementById(address + ",SouthAfrica"), myOptions);
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.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);
}
});
}

Categories