How to specify location in google map? - javascript

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.

Related

How to get coordinates of a place using google map javascript api

I have a address, i want to display it on the map and also get the lat/lng
<body>
<div id="floating-panel">
<input id="address" type="textbox" value="Sydney, NSW">
<input id="submit" type="button" value="Geocode">
</div>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
});
}
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
//////////////////////////////////////////
console.log(results[0].geometry.location);
//////////////////////////////////////////
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
I got this:
the map works fine but i can't get the lng/lat.
How can i get that using the Maps JavaScript API or i have to use other map API like Geocoding API
As you can see from your own screenshot, in order to retrieve the calculated values of lat/long, you need to treat those attributes like functions.
let latVal = results[0].geometry.location.lat();
let lngVal = results[0].geometry.location.lng();

(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

Google Maps API requires refresh to work correctly

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.

adding strings in javascript

I am working on creating a page using html and javascript.
I have json file that proves inputs to some of the contents i need.
What Im trying to do is to have address variable setup so that google map API can be displayed on my page.
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var address = cmpyJson[jobCmpyID].company_name+" Company, "+locJson[jobLocID].location_name;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 11,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{ content: '<b>'+address+'</b>',
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:200px;"></div>
</body>
</html>
above is part of the code.
the address variable has to look like
var address= "google Company, Austin, TX"
for google to recognize it properly.
if i know for fact that json returns exactly what im asking, what could be the problem here? how could i go about fixing it?
updated to ease some confusions.
when i view the source code on my website, i see that returned values are strings...
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var address =Oracle+" Company, "+San Francisco, CA;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 11,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{ content: '<b>'+address+'</b>',
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:200px;"></div>
</body>
assuming that all of these variables exist, the following line should be:
var address = cmpyJson[jobCmpyID].company_name+" Company, "+locJson[jobLocID].location_name;
I just removed all of the curly brackets to make it syntactically correct.
If address is supposed to produce a string, and pull in parts from the cmpJson object, then do this:
var address =cmpyJson[jobCmpyID].company_name +" Company, "+
locJson[jobLocID].location_name;
You don't need the {{ }} around the JSON object references. Also, if you plan to pass this into google, you need to encode it.

Display the Latitude and Longitude of a searched address on my sites Google-Map using API

I have a section on a website I am developing where the user can input their address into the Google Geocode Api and their homes location is displayed, once the map is displayed the marker cannot be moved neither does the right click bring up the "What's Here" option.
What I am actually trying to get as well as the map view are the co-ordinates for that address ideally with the ability to allow the user to fine tune the marker to lets say the front entrance porch and have the Latitude and Longitude displayed either on the screen or inside of an input field.
Thanks for looking at this for me, I know very little about Javascript programming and greatly appreciate any help that you can offer.
Kind Regards
Ian.
The basic code I've used so far is below:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"> </script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(51.915892, -0.660751);
var mapOptions = {
zoom: 18,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
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);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
For that right click function, you'll have to create your own on right clicked location.
google.maps.event.addListener(map, "rightclick", function(event) {
//your code here on right click
});
here is answer to your first query that you want user to fine tune marker by dragging and get lat, lng inside input boxes.
<html>
<head>
<title></title>
<script type='text/javascript' src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(51.915892, -0.660751);
var mapOptions = {
zoom: 18,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
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,
draggable: true
});
google.maps.event.addListener(marker,'dragend',function(event) {
document.getElementById('lat').value = event.latLng.lat();
document.getElementById('lng').value = event.latLng.lng();
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<style>
#map-canvas {
width: 1000px;
height: 500px;
}
</style><div id="map-canvas"></div>
<input type="text" id="address" placeholder="type your address here"/>
<button onclick="codeAddress()">Show on map</button>
<br>
<br>
<input type="text" id="lat" />
<br>
<input type="text" id="lng" />
</body>
</html>

Categories