Google maps api key php

Add Custom Marker Icons to Google Map Dynamically from the Database with PHP and MySQL

Google Maps API provides an easy way to embed the map on the web page. The specific location can be marked on the Google Map using a marker. The marker with InfoWindow helps to add some information about the location. You can add multiple markers with InfoWindow to the Map using Google Maps JavaScript API.

Google Map with multiple markers is very useful when you want to add multiple locations in a single map. Generally, static markers are added to Google Maps. But, if you want to add dynamic locations from the database, it can be easily done with PHP and MySQL. You can add multiple markers with Info Window to Google Map dynamically from the database with PHP and MySQL. In this tutorial, we will show you how to add custom markers with Info Window to Google Maps dynamically from the database using PHP and MySQL.

In the example code, we will implement the following functionality.

  • Embed Google Maps on the website.
  • Fetch dynamic locations from the database.
  • Add multiple markers with Info Window to the Google Map.
  • Fetch dynamic marker icons from the database.
  • Change and add custom icon/images to markers.
Читайте также:  Java массив строка разделитель

Get an API Key

An API key is required to use the Google Maps JavaScript API. You need to specify the API key on API call to authenticate with Google Maps JavaScript API. So, before you begin to embed Google Map on the website, create an API key on the Google Developers Console.

  • Go to the Google Developers Console.
  • Select the project from the Project drop-down menu at the top. If you don’t have an existing project, create a new one.
  • In the left navigation pane, select the APIs & Services » Credentials.
  • In the Credentials page, select Create credentials » API key.
  • The API key will be created and a dialog will appear with newly created API key.

Copy the API key for later use in the script on Google Maps JavaScript API request.

Create Database Table

To store the dynamic locations information and marker images a table is required in the database. The following SQL creates a locations table with some basic fields in the MySQL database.

CREATE TABLE `locations` ( `id` int(11) NOT NULL AUTO_INCREMENT, `latitude` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `longitude` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `info` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `icon` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Marker icon', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect and select the database. Specify the database host ( $dbHost ), username ( $dbUsername ), password ( $dbPassword ), and name ( $dbName ) as per your MySQL database credentials.

// Database configuration 
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld";

// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check connection
if ($db->connect_error) <
die(
"Connection failed: " . $db->connect_error);
>

Fetch Location and Marker Image Info from Database

The latitude and longitude are fetched from the database using PHP and MySQL.

  • The first result set is used to generate multiple markers and custom icons information (location, latitude, longitude, and icon image source).
  • The second result set is used to generate the content of the info windows.
// Include the database configuration file 
require_once 'dbConfig.php';

// Fetch the marker info from the database
$result = $db->query("SELECT * FROM locations");

// Fetch the info-window data from the database
$result2 = $db->query("SELECT * FROM locations");
?>

Add Multiple Markers with Custom Images

Load the Google Map JavaScript API and specify an API key in the key parameter.

script src="https://maps.googleapis.com/maps/api/js?key=Your_API_KEY">script>

The following JavaScript code adds multiple markers with custom icons to Google Map from the database in PHP.

  • The initMap() is a custom JavaScript function that initializes Google Maps.
  • Define the Google Maps object and attach the map to the HTML element.
  • Fetch the latitude, longitude, and marker icon image URL from the database and generate position array for multiple markers ( markers ).
  • Fetch the location info from the database and generate array for the content of info windows ( infoWindowContent ).
  • Add multiple markers with dynamic locations and custom icon to Google Map.
  • Add info window with dynamic content to the markers.
  • Set zoom level of the Google Map.

Load initMap() function to initialize the Google Map.

script> function initMap( ) < var map; var bounds = new google.maps.LatLngBounds(); var mapOptions = < mapTypeId: 'roadmap' >; // Display a map on the web page map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions); map.setTilt(100); // Multiple markers location, latitude, and longitude var markers = [  if($result->num_rows > 0) < 
while(
$row = $result->fetch_assoc()) <
echo
'["'.$row['name'].'", '.$row['latitude'].', '.$row['longitude'].', "'.$row['icon'].'"],';
>
>
?> ]; // Info window content var infoWindowContent = [ if($result2->num_rows > 0) <
while(
$row = $result2->fetch_assoc()) ?> ['div class="info_content">' + 'h3>
echo $row['name']; ?> h3>
' + 'p>
echo $row['info']; ?> p>
' + ' div>'], >
>
?> ]; // Add multiple markers to map var infoWindow = new google.maps.InfoWindow(), marker, i; // Place each marker on the map for( i = 0; i < markers.length; i++ ) < var position = new google.maps.LatLng(markers[i][1], markers[i][2]); bounds.extend(position); marker = new google.maps.Marker(< position: position, map: map, icon: markers[i][3], title: markers[i][0] >); // Add info window to marker google.maps.event.addListener(marker, 'click', (function(marker, i) < return function( ) < infoWindow.setContent(infoWindowContent[i][0]); infoWindow.open(map, marker); > >)(marker, i)); // Center the map to fit all markers on the screen map.fitBounds(bounds); > // Set zoom level var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) < this.setZoom(14); google.maps.event.removeListener(boundsListener); >); > // Load initialize function google.maps.event.addDomListener(window, 'load', initMap); script
>

Embed Google Map with Custom Marker Icons

Define an HTML element to embed the Google Map with multiple markers and Info Windows on the web page. Specify the element ID ( mapCanvas ) in the Google Map object.

CSS Code

Use CSS to set the height and weight of the Google map container.

#mapCanvas < width: 100%; height: 650px; >

Conclusion

Google Map marker icon can be easily changed using JavaScript. Use our example script to change and add a custom image to marker icons in Google Maps. You can add markers and icons dynamically from the database with PHP and MySQL. Not only the marker but also you can add dynamic content to info window of the Google Map.

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

If you have any questions about this script, submit it to our QA community — Ask Question

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Adds Google Maps API KEY to any theme or plugin retroactively.

License

AyeCode/google-maps-api-key

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

readme.txt

=== API KEY for Google Maps === Contributors: stiofansisland, paoltaia Tags: Google Maps, Google Maps KEY, Google Maps API KEY, Google Maps callback, Google Maps API callback Donate link: https://wpgeodirectory.com Requires at least: 3.1 Tested up to: 6.2 Stable tag: 1.2.8 License: GPLv2 License URI: http://www.gnu.org/licenses/gpl-3.0.html Retroactively add Google Maps API KEY to any theme or plugin. == Description == Retroactively add Google Maps API KEY to any theme or plugin. Simply activate, go to Settings>Google API KEY and enter your key. The plugin will then attempt to add this key to all the places it is needed on the front of your website. NOTE: this will only work if the Google API has been added as per WordPress standards) Since January 2023 Google Maps JavaScript API requires callback parameter. This plugin also fixes JavaScript Error: [Loading the Google Maps JavaScript API without a callback is not supported](https://developers.google.com/maps/documentation/javascript/url-params#required_parameters). The plugin was created by the GeoDirectory team:  == Installation == = Minimum Requirements = * WordPress 3.1 or greater * PHP version 5.2.4 or greater * MySQL version 5.0 or greater = Automatic installation = Automatic installation is the easiest option. To do an automatic install log in to your WordPress dashboard, navigate to the Plugins menu and click Add New. In the search field type Google Maps API KEY and click Search Plugins. Once you've found the plugin you install it by simply clicking Install Now. = Manual installation = The manual installation method involves downloading the plugin and uploading it to your webserver via your favourite FTP application. The WordPress codex will tell you more [here](http://codex.wordpress.org/Managing_Plugins#Manual_Plugin_Installation). = Updating = Automatic updates should seamlessly work. We always suggest you backup up your website before performing any automated update to avoid unforeseen problems. == Frequently Asked Questions == Ask and they shall be answered == Screenshots == 1. Settings page. 2. Generate API KEY. 3. Copy API KEY, paste in Settings and save. == Changelog == = 1.2.8 (2023-03-30) = * WordPress v6.2 compatibility - CHANGED = 1.2.7 (2023-02-02) = * Add .gitattributes file - ADDED * Generate Google API Key is no longer working - FIXED * Loading the Google Maps JavaScript API without a callback is not supported - CHANGED = 1.2.3 = * Plugin version update - CHANGED = 1.2.2 = * Compatibility checked with WordPress 6.0 - CHECKED * Now tries to add api key even if no key param is found - CHANGED * Now only users with "manage_options" ability can update the API key - SECURITY = 1.2.1 = * Compatibility checked with WordPress 5.9 = 1.2.0 = iframe api generation broken (by Google iframe restrictions) changed to new window popup - FIXED Updated Generate API KEY button to add access for all APIs - CHANGED = 1.1.0 = Added a Generate API KEY button for easier generation of API KEY - ADDED = 1.0.0 = initial release == Upgrade Notice ==

About

Adds Google Maps API KEY to any theme or plugin retroactively.

Источник

Оцените статью