I have created an API that returns a json consisting of a latitude and longitude, and wanted to pass that into the Google Maps API, to get the corresponding map.
To get the data from my API I created an ajax request as follows:
scripts.js:
$(document).ready(function(){
$("button").click(function(){
$.get("my url", function(data, status){
//do something with this data
});
});
});
After I get the JSON from this, I want to pass the latitude and longitude to the script that Google Maps API provides as follows, inside my index.html.
index.html
<body>
<h1> JOS Map App </h1>
<button>Send an HTTP GET request to a page and get the result back</button>
<script type="text/javascript" src = "js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src = "js/scripts.js"></script>
<div id="map"></div>
<script> //THIS ONE!!
function initMap() {
var uluru = {lat: , lng: };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
Basically, I want to be able to pass the latitude and longitude from my GET request to this script so that I can pass them into the google maps API call. I am fairly new to jQuery, so have no idea how to do this.
Thanks!
Why not just pass the lat/lng as parameters to the Google Maps init()?
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("my url", function(data, status){
initMap(data.lat, data.lng);
});
});
});
function initMap(lat, lng) {
var uluru = {lat: lat, lng: lng};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
You can move that initMap() function to scripts.js. Just make sure you're loading Google Maps API before your scripts.js.
Related
I'm new to php and I'm trying to display a google maps location with dynamic coordinates. Here's the code where I do the queries:
$longitudine="select longitudine from sedi, stati, tappe, spedizioni where $idSpedizione=tappe.spedizione and tappe.stato=idStato and sedi.citta=tappe.luogoInizio group by data desc limit 1;";
$longi=$conn->query($longitudine);
$longg=mysqli_fetch_array ($longi);
$latitudine="select latitudine from sedi, stati, tappe, spedizioni where $idSpedizione=tappe.spedizione and tappe.stato=idStato and sedi.citta=tappe.luogoInizio group by data desc limit 1;";
$lati=$conn->query($latitudine);
$lat=mysqli_fetch_array ($lati);
And here is the code:
<style>
#map {
height: 400px;
width: 100%;
}
</style>
<div id="map"></div>
<script>
function initMap() {
var uluru = { lat: 47.37, lng: 9.200000 };
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: uluru,
});
var marker = new google.maps.Marker({
position: uluru,
map: map,
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap&libraries=&v=weekly"
></script>
Basically I want to set the coordinates with the values of the queries, but when I try it doesn't show me the map. Can anyone help me?
If your both php and script code as above are on the same page, you can add php variables to your script's uluru variable as:
var uluru = { lat: <?php echo floatval($lat["latitudine"]) ?>, lng: <?php echo floatval($longg["longitudine"]) ?> };
Please note its not a standard way to add php variables to your script code like that but it may work on your code. You can try.
P.S: Please don't reveal your API key as you did in your question. Please edit and change it to MY_API_KEY or something in your question above.
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
I am trying to make a mashup application that gets json output from a restful webservice. the mashup application fetches latitude and longitude data from json response and then points it in an embedded good map.
<html>
<form>
Post Code:<br>
<input type="text" id="postcode"><br>
<button onclick="getdata()">Submit</button>
</form>
<h1>Location on Google Map</h1>
<div id="map" style="width:400px;height:400px;background:yellow"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getdata() {
var value1 = $("input#postcode").val();
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:8080/getlocation?postcode=" + value1,
"type": "POST",
"method": "GET"
}
$.ajax(settings).done(function(response) {
data = JSON.parse(response);
console.log(data['4000']['Latitude']);
var lat = data['4000']['Latitude'];
var lng = data['4000']['Longitude'];
init(lat, lng);
});
function init(lat, lng) {
latlng = new google.maps.LatLng(lat, lng);
var mapOptions = {
center: new google.maps.LatLng(lat, lng),
zoom: 20,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var customMarker = new google.maps.Marker({
position: latlng,
map: map,
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=getdata"></script>
</html>
However I am unable to pass different values to the parameters 'postcode' in
"http://localhost:8080/getlocation?postcode=". The values passed should be like 4010,4011 etc
I think its because your <script src="https://maps.googleapis.com/maps/api/js?callback=getdata"></script> is being initiated AFTER your custom script. The google maps api should be declared BEFORE your code. Place it above your <script> tags containing the custom code
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.
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.