Using google places api with google geocode api together - wordpress

I am using google places autocomplete api and now I want to get the geocode of that address and display that area on map.This is my code...
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="searchTextField" type="text" size="50">
</body>
I know there is google geocde api but I really dont know how to do that.
I m doing all this in wordpress. Anybody has idea about this???

Looks like that's what you need:
<style>
#map-canvas {
width: 500px;
height: 500px;
}
</style>
Then, the JS
function initialize() {
// initial zoom and position
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(-25.3, 133.8)
};
// create Map instance
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
// get input reference
var input = document.getElementById('searchTextField');
// create instance of autocomplete
var autocomplete = new google.maps.places.Autocomplete(input);
// listen for changes
google.maps.event.addListener(autocomplete, 'place_changed', function() {
// get the selected place
var place = this.getPlace();
// if there's a geometry available
if (place.geometry) {
// move the map to the position
map.panTo(place.geometry.location);
// update the zoom
map.setZoom(15);
// log the position
console.log(place.geometry.location.lat(),place.geometry.location.lng() )
}
})
}
More info: https://developers.google.com/maps/documentation/javascript/places-autocomplete

Related

Launch Google Maps On Blazor

I am trying to launch Google maps on my Server side Blazor app using JSInterop. I seem to have tried just about everything but can't get the map to show. Unfortunately there is very little samples if any about it on the internet since it's a fairly new framework and I am equally just getting my feet wet on Blazor myself, so I am probably doing a whole lot of things wrong. Any nudge in the right direction would be appreciated.
In my component file, I have:
#page "/MapTest"
#inject IJSRuntime JSRuntime
<style>
#map {
width: 60%;
height: 60%;
}
</style>
<h1>Display Google Map</h1>
<div #ref="map" id="map"></div>
#code {
ElementReference map; // reference to the DIV
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await JSRuntime.InvokeVoidAsync("Showgooglemap", null);
//StateHasChanged();
}
}
On my _Host.cshtml file, I have:
<script src="_framework/blazor.server.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=xxxmykeyxxx&v=3"></script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(40.716948, -74.003563);
var options = {
zoom: 14, center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById
("map"), options);
}
//google.maps.event.addDomListener(window, 'load', initialize);
//i tried wrapping the call in a function to see if it helps
function Showgooglemap() {
google.maps.event.addDomListener(window, 'load', initialize);
}
</script>
Welcome #flylily, you are almost done. I run your code in my sample Blazor-server-side project. I only change two things. One is change height from percentage to pixel (for percentage height HTML 5) and another is invoke initialize function insteed of Showgooglemap becasuse initialize function already initialize your map on page load or first render. The complete codes are in following, try with these...
_Host.cshtml file,
<script src="_framework/blazor.server.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key={{put-your-api-key}}&v=3"></script>
<script>
function initialize() {
var latlng = new google.maps.LatLng(40.716948, -74.003563);
var options = {
zoom: 14, center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById
("map"), options);
}
</script>
MapTest.razor component,
#page "/MapTest"
#inject IJSRuntime JSRuntime
<h1>Display Google Map</h1>
<div id="map" style="height:500px;width:100%;">
</div>
#code{
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("initialize", null);
StateHasChanged();
}
}
}
Finally, run your application & enjoy.
You can use the package BlazorGoogleMaps from rungwiroon as well. It supports
Map
Marker
Symbols
InfoWindow
Polygon, LineString, Rectangle, Circle
Routes
Coordinates
Bounds
Styles
and is available on Github and NuGet.
I'm using it and it works really well.
You can use this Nuget package. It will give your Blazor app full control over Google Static and JavaScript Maps API as well.
Usage can be complicated so recommend to read the documentation for more details and check the demo app.
Other Nuget package can help you access Browsers Geolocation services as well. See Geo JS docs as well as demo app.

Event listener to delete individual markers when they are clicked, only acts on last created marker

Hello and thanks in advance for your help!
The following test code:
1) Uses PHP to get lat/lng data from a mySQL database, and then uses that data to form a JavaScript array with initialization data. WORKS FINE.
2) Uses the initialized JavaScript array to create markers. WORKS FINE.
3) Allows (left) clicks to create new markers (more code will be added later to add those new marker locations back into the database). WORKS FINE.
4) Allows RIGHT-clicks to delete a marker using marker.setMap(null) - either the preloaded markers from the database, or newly created user markers. USER MARKERS DELETE PROPERLY, PRE-LOADED MARKERS DO NOT DELETE PROPERLY, AS DESCRIBED BELOW.
5) Both the preloaded markers, and the newly created ones are stored in the array "markers" using the statement markers.push(marker). SEEMS TO BE OK.
Everything works, except the right-click deletion of the PRELOADED markers. (The right-click deletion of user created markers works fine.) Any right-click on any preloaded marker, only deletes the LAST preloaded marker. It's as if the delete event listener were outside and after the loop that sets the preloaded markers, but it is inside that loop.
I think the faulty section is the one with the leading comment "show prev clicks in database". Any ideas would be greatly appreciated! I'm very new at Google Maps API v3, so it's probably something obvious that I'm just missing or misunderstanding. Thanks again!
<!DOCTYPE html>
<html>
<head>
<title>Marker Test</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas, #map_canvas {
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
<?
// Generate JavaScript array initialization from database
$username="REDACTED";
$password="REDACTED";
$database="REDACTED";
$con=mysql_connect(localhost,$username,$password);
#mysql_select_db($database,$con) or die( "Unable to select database");
$query="SELECT * FROM pool where (record_id >= 1765) AND (record_id <= 1769)";
/*
$query="SELECT * FROM pool where (record_id <= '$marker_end') AND (record_id >= '$marker_start')";
$query="SELECT * FROM pool where session = '$session'";
*/
$result=mysql_query($query,$con);
$length=mysql_num_rows($result);
$length_count=1;
if ($result) {
echo "var PreviousClicks = [\n";
while($row = mysql_fetch_array($result)) {
$_lat=$row['google_lat'];
$_lng=$row['google_lng'];
$_record_id=$row['record_id'];
echo "{\n";
echo "lat: $_lat,\n";
echo "lng: $_lng,\n";
echo "title: \"$_record_id\"\n";
echo "}";
if($length_count<$length) {echo ",\n";} else {echo "\n";}
$length_count++;
} // end while
echo "];";
} // end if
mysql_close();
?>
</script>
<script type="text/javascript">
var map;
var markers = [];
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
title: "A",
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
marker.setMap(null);
});
markers.push(marker);
} //end addMarker function
function initialize() {
// currently manual center initialization
var startLoc = new google.maps.LatLng(33.037380,-117.090431);
var mapOptions = {
zoom: 16,
center: startLoc,
mapTypeId: google.maps.MapTypeId.TRAFFIC
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
// show prev clicks in database ------------------------------------------------------------------
for (i = 0; i < PreviousClicks.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(PreviousClicks[i].lat, PreviousClicks[i].lng),
title: PreviousClicks[i].title,
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
marker.setMap(null);
});
markers.push(marker);
} // end for
// end "show prev clicks in database" section ----------------------------------------------------
} // end function initialize
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas">
</div>
</body>
</html>
Inside a marker's event handler, this refers back to the marker. Therefore :
this.setMap(null);
will remove the marker from the map.
But more can be done with this code. In particular :
Avoid repeating code by using addMarker() to add both new and previous markers.
When markers are removed, also remove them from the markers array.
Both can be achieved as follows :
function addMarker(event) {
var marker = new google.maps.Marker({
position: event.latLng,
title: event.title || "A",
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
this.setMap(null);
//Remove the marker from the markers array.
for(i=0; i<markers.length; i++) {
if(markers[i] == this) {
removed = markers.splice(i, 1);
break;
}
}
});
markers.push(marker);
}
function initialize() {
...
google.maps.event.addListener(map, 'click', addMarker);
...
for (i = 0; i < PreviousClicks.length; i++) {
addMarker({
latLng: new google.maps.LatLng(PreviousClicks[i].lat, PreviousClicks[i].lng);
title: PreviousClicks[i].title
});
}
}

How to save map drawing state (Polygon, Polyline, Markers)

I want to enable drawing on Google Maps like (see this example)
When user finish with drawings he will click on save button to save his drawings in Database or KML file, anything :) .. I do not know how to the save part? Could anyone help me
Here, http://jsfiddle.net/X66L4/1/ try drawing some circles, click on SAVE, then edit the circles by switching to the hand cursor and SAVE again to see the changes.
I show an example to save circles' data, the main idea is to keep a global array for each drawing type (line, polygon, marker, circle), and use a listener on the drawing manager to detect each type being drawn (complete).
var circles = [];
google.maps.event.addDomListener(drawingManager, 'circlecomplete',
function(circle) {
circles.push(circle);
});
The reason to save the entire reference to the drawn object is to continue tracking changes. So you will need an array and listener for each type of drawing.
Then, when you want to save the data (you may wish to do so at every edit), iterate through the arrays and extract the minimum information to rebuild it (center, radius, path, latLng, and so on.)
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body, #map_canvas { margin: 0; padding: 0; height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing"></script>
<script type="text/javascript">
var myOptions = {
center: new google.maps.LatLng(-25,177.5),
zoom: 3,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map;
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.CIRCLE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [google.maps.drawing.OverlayType.CIRCLE]
},
circleOptions: {
editable: true
}
});
drawingManager.setMap(map);
var circles = [];
google.maps.event.addDomListener(drawingManager, 'circlecomplete', function(circle) {
circles.push(circle);
});
google.maps.event.addDomListener(savebutton, 'click', function() {
document.getElementById("savedata").value = "";
for (var i = 0; i < circles.length; i++) {
var circleCenter = circles[i].getCenter();
var circleRadius = circles[i].getRadius();
document.getElementById("savedata").value += "circle((";
document.getElementById("savedata").value +=
circleCenter.lat().toFixed(3) + "," + circleCenter.lng().toFixed(3);
document.getElementById("savedata").value += "), ";
document.getElementById("savedata").value += circleRadius.toFixed(3) + ")\n";
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<button id="savebutton">SAVE</button>
<textarea id="savedata" rows="8" cols="40"></textarea>
<div id="map_canvas"></div>
</body>
</html>
In my experience, it's easier to use map's dataLayer then the drawing manager.
Try out this fiddle.
FiddleLink
Showing the controls:
map.data.setControls(['Polygon']);
map.data.setStyle({
editable: true,
draggable: true
});
in this function you can see the Create, Read (localStorage) and Remove (not in that order):
function loadPolygons(map) {
var data = JSON.parse(localStorage.getItem('geoData'));
map.data.forEach(function (f) {
map.data.remove(f);
});
console.log(data);
map.data.addGeoJson(data)
}

Why Marker Manager doesn't work?

I would use MarkerManager to group neighboring marker in one, I tested an example but it does not work. Different markers are displayed well, but they are not together when they should. The manager is not working as it should, I do not understand why.
<html>
<head>
<title>Test GMap - MarkerManager</title>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/src/markermanager.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer_compiled.js"></script>
</head>
<body>
<div id="my-map" style="width:100%;height:700px"></div>
<script>
var maCarte = '';
function initialisation(){
var centreCarte = new google.maps.LatLng(47.389982, 0.688877);
var optionsCarte = {
zoom: 5,
center: centreCarte,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
maCarte = new google.maps.Map(document.getElementById("my-map"), optionsCarte);
// Create a new instance of the MarkerManager
var mgr = new MarkerManager(maCarte);
google.maps.event.addListener(mgr, 'loaded', function() {
console.log('loaded Map');
// Create marker array
var markers = [];
// Loop to create markers and adding them to the MarkerManager
for(var i = 0; i < 50; i += 0.1) {
var marker = new google.maps.Marker({position: new google.maps.LatLng(47.389982 + i, 0.688877 + i)});
markers.push(marker);
}
//var markerCluster = new MarkerClusterer(map, markers);
// Add the array to the MarkerManager
mgr.addMarkers(markers, 8);
// Refresh the MarkerManager to make the markers appear on the map
mgr.refresh();
});
}
google.maps.event.addDomListener(window, 'load', initialisation);
</script>
</body>
Can someone help me?
thank you very much
Your page works for me, but the markers are not immediately visible when the page loads. This is because of the zoom setting you have on line 34:
mgr.addMarkers(markers, 8);
if you set that to a lower number (say, 4) the markers will be visible when zoomed further out.

Google Map V3 API Not working in localhost

I copied following javascript code from google maps documentation, but it doesn't work, it only shows a white blank page, nothing loads.
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Map Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<!--
Include the maps javascript with sensor=true because this code is using a
sensor (a GPS locator) to determine the user's location.
See: http://code.google.com/apis/maps/documentation/javascript/basics.html#SpecifyingSensor
-->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var map;
function initialize() {
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
Since v3 require api key what's wrong with it? I checked in google chrome and firefox but no clue.
Looks like you are missing a closing html tag, unless that is a typo.
Add this </html> at the bottom of the page.
You need to provide a center location to create your map. In your initialize() function change the map options to include the location you want to start with:
var myCenter = new google.maps.LatLng(60.0,105.0);
var myOptions = {
zoom: 6,
center: myCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
When (or if) you get a location from the geolocation service the center will be changed by your code.
Old question, will answer anyhow in case anyone else lands here.
I ended up using a slightly different implementation to get this to work:
<script type="text/javascript">
function initialize() {
var mapOptions = {zoom: 8, center: new google.maps.LatLng(-34.397, 150.644)};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp'+
'&key={{API_KEY}}&sensor=false&callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript();
</script>
The part that I had to add to get it to work from other (nearly identical) versions of this, was the () at the end of loadScript(). The implicit function call simply was not happening.
You will need to replace {{API_KEY}} with your own. I am not sure if this is required, but it was part of what led me to a working implementation.
If you do not have one, follow the steps listed here

Resources